valentina moreno
valentina moreno

Reputation: 1

I need to read a number, then I need to read a string with whitespaces but my program does not let me read a string it skips the second scan

#include <stdio.h>

int main(void) {

char user_string[100];
int n;

printf("Enter a number greater than 0:");
scanf("%d",&n);

printf("Enter %d strings with white spaces: ", n);
scanf("%[^\n]", user_string);
printf("The string you entered is: %s", user_string);

return 0;

}

output: Enter a number greater than 0:5 Enter 5 strings with white spaces: The string you entered is:

Upvotes: 0

Views: 20

Answers (1)

chux
chux

Reputation: 153338

Failed to consume '\n'

scanf("%d",&n); does not consume a trailing '\n'. That prevents the following scanf("%[^\n]", .... from reading anything.

Allow the scanf("%[^\n]", user_string); to consume leading white-space: scanf(" %[^\n]", user_string); (space added).

Missing width

scanf("%[^\n]", user_string); is worse than gets. Do not use "%[^\n]" without a width limit.

// scanf("%[^\n]", user_string);
scanf(" %99[^\n]", user_string);

Missing return value check

Add a check.

if (scanf(" %99[^\n]", user_string) != 1) {
  fprintf(stderr, "Bad input\n");
  exit(EXIT_FAILURE); // or other action.
}

Tip: Read user input with fgets(). Do not use scanf() until you know why it is bad.


Detail: "then I need to read a string with whitespaces" is a faulty goal. In C, a string is a sequence of characters followed by a null character. Users do not normally ever enter a null character.

A more correct goal may be "read a line ...". (Characters up to and including a '\n'.)

Upvotes: 0

Related Questions