0

I am stuck on a part of an assignment I am writing.

When I am typing in the postalCode (which is A8A 4J4) it shows

output1

output2

It is supposed to be:

Postal code: A8A 4J4
City: Toronto

It is skipping the option to enter the City.

I've tried %[^\n] and it still skips the option to enter the City.

My current code is:

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);

I saw a post about this already but the answers there didn't help. I already tried the [^\n] in my scanf.

jwpfox
  • 5,124
  • 11
  • 45
  • 42
  • Possible duplicate: https://stackoverflow.com/questions/28197006/the-scanf-function-the-specifer-s-and-the-new-line or https://stackoverflow.com/questions/29905009/reading-newline-from-previous-input-when-reading-from-keyboard-with-scanf – Jerry Jeremiah Oct 26 '17 at 22:31
  • Possible duplicate: https://stackoverflow.com/questions/45394221/newline-character-n-in-scanf or https://stackoverflow.com/questions/15740024/scanf-asking-twice-for-input-while-i-expect-it-to-ask-only-once – Jerry Jeremiah Oct 26 '17 at 22:39
  • You could try `scanf("%s ", &address.postalCode);` to eat the trailing whitespace or `scanf(" %40s", address.city);` to eat the leading whitespace. – Jerry Jeremiah Oct 26 '17 at 22:40

2 Answers2

1

The better for string input is fgets as scanf ("%[^\n]%*c", &address.city); does not work well if the the line is only "\n" or too long. Stick with fgets().

 fgets(address.city,40,stdin);

EDIT: If you still want to use scanf use like this

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

it will scan characters until it finds '\n'

krpra
  • 466
  • 1
  • 4
  • 19
0

Put the & on your reference to address.city like this

scanf("%40s", &address.city);
Grantly
  • 2,546
  • 2
  • 21
  • 31