2017-10-26 3 views
0

Ich bin auf einem Teil einer Aufgabe fest, die ich schreibe.Brauchen Sie Hilfe über die Eingabe von Zeichenfolgen und Drucken

Als ich in der postal tippe (die A8A 4J4 ist) es zeigt

output1

output2

Es soll sein:

Postal code: A8A 4J4 
City: Toronto 

Es ist Überspringen der Option in die Stadt kommen.

Ich habe versucht %[^\n] und es überspringt immer noch die Option, die Stadt eingeben.

Mein aktueller Code ist:

if (option == 'y' || option == 'Y') { 
    printf("Please enter the contact's apartment number: "); 
    scanf("%u", &address.apartmentNumber); 

    printf("Please enter the contact's postal code: "); 
    scanf("%s", &address.postalCode); 
} 

if (option == 'n' || option == 'N') { 
    printf("Please enter the contact's postal code: "); 
    scanf("%s", &address.postalCode); 
} 

printf("Please enter the contact's city: "); 
scanf("%40s", address.city); 

printf("Postal code: %s\n", address.postalCode); 
printf("City: %s\n", address.city); 

sah ich einen Beitrag über das schon aber die Antworten dort nicht helfen. Ich habe bereits versucht, die [^ \ n] in meinem scanf.

+0

Mögliche doppelte findet: https://stackoverflow.com/questions/ 28197006/the-scanf-function-the-specifier-s-und-die-neue-line oder https://stackoverflow.com/questions/29905009/reading-newline-from-previous-input-when-reading-from- keyboard-with-scanf –

+0

Mögliches Duplikat: https://stackoverflow.com/questions/45394221/n ewline-character-n-in-scanf oder https://stackoverflow.com/questions/15740024/scanf-asking-twice-for-input-while-i-expect-it-to-ask-only-once –

+0

Sie könnten Probieren Sie 'scanf ("% s ", & address.postalCode);' um den nachgestellten Whitespace oder 'scanf ("% 40s ", address.city) zu essen;' um den führenden Whitespace zu essen. –

Antwort

0

Setzen Sie die & auf Ihrem Verweis auf address.city wie diese

scanf("%40s", &address.city); 
+0

Ich habe das gemacht, dasselbe, es überspringt es. – IlllIIIlIlIIl

+0

Oder verwenden Sie dieses scanf ("% s", & address.city); Sie brauchen das kaufmännische Und-Zeichen. – Grantly

+1

Ich habe alles versucht und gefunden, dass 'scanf ("% [^ \ n] ", & address.postalCode); 'und' scanf ("% 40s", address.city); 'hat funktioniert. Danke für die Hilfe. – IlllIIIlIlIIl

1

Je besser für String-Eingang fgets als scanf ("%[^\n]%*c", &address.city) ist; funktioniert nicht gut, wenn die Linie nur "\n" oder zu lang ist. Stick mit fgets().

fgets(address.city,40,stdin); 

EDIT: Wenn Sie noch scanf Einsatz wie dieser

scanf (" %[^\n]%*c", &address.city) 

es Zeichen verwenden möchten, scannen, bis es '\n'