Problem mit sscanf
-
Hallo zusammen,
ich spiele momentan ein bisschen mit der sscanf() Funktion rum.
Kann mir jemand erklären bzw. zeigen wo mein Fehler bei dem folgenden Code ist:/* sscanf example */ #include <stdio.h> int main () { char sentence []="$5&&6&|Test1&&Test2"; char str1 [125], str2[125]; int a, b; sscanf (sentence,"$%d&&%d&|%s&&%s", &a, &b, str1, str2); printf("a: %i\nb: %i\nstr1: %s\nstr2: %s\n", a, b, str1, str2); return 0; }
Problem ist das str2 immer leer ist.
Vielen Dank!
-
Lies dir mal den Teil zu format strings durch: http://www.cplusplus.com/reference/cstdio/scanf/
Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
Es ist also ganz richtig, dass nichts in str2 gespeichert wird, das Programm kann nicht "wissen", dass du nur "Test1" in str1 speichern willst.
-
Die Strings müssen durch Leerzeichen getrennt werden, sonst erkennt er nur einen String.
char sentence[] = "$5&&6&| Test1 && Test2"; char str1[125], str2[125]; int a, b; *str1 = *str2 = '\0'; sscanf(sentence, "$%d&&%d&| %s && %s", &a, &b, str1, str2); printf("a: %i\nb: %i\nstr1: %s\nstr2: %s\n", a, b, str1, str2);
-
asdfsx schrieb:
Lies dir mal den Teil zu format strings durch: http://www.cplusplus.com/reference/cstdio/scanf/
Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.
Es ist also ganz richtig, dass nichts in str2 gespeichert wird, das Programm kann nicht "wissen", dass du nur "Test1" in str1 speichern willst.
Naja, man kann aber schon vermuten, daß die Funktion das könnte, weil die Trennzeichen (hier: &&) definiert sind - leider ist die Funktion aber zu dumm dafür
-
ralros schrieb:
Die Strings müssen durch Leerzeichen getrennt werden, sonst erkennt er nur einen String.
char sentence[] = "$5&&6&| Test1 && Test2"; char str1[125], str2[125]; int a, b; *str1 = *str2 = '\0'; sscanf(sentence, "$%d&&%d&| %s && %s", &a, &b, str1, str2); printf("a: %i\nb: %i\nstr1: %s\nstr2: %s\n", a, b, str1, str2);
Den Ausgangsstring zu ändern ist keine Lösung
Was soll Zeile 5?
Wieso die Leerzeichen im Formatstring?
-
Dafür gibt es den Formatspecifier %[
sscanf (sentence,"$%d&&%d&|%[^&]&&%s", &a, &b, str1, str2);