Pregunta

I'm trying to use two scanf's to read a string and then an integer. The program waits for me to enter the string, i press enter and then doesn't wait for me to insert the integer. The code i'm using:

printf("Insert the name of the author to search: ");
scanf("%300s", author);

printf("Insert the year: ");
scanf("%d", &year);

Any suggestions?

¿Fue útil?

Solución

The conversion specifier "%s" breaks on whitespace.

If you enter, for instance, "John Smith", the variable author will have "John" and the rest of the input will be used for year.

Always validate the return value of (most) library functions.

printf("Insert the name of the author to search: ");
if (scanf("%300s", author) != 1) /* error */;

printf("Insert the year: ");
if (scanf("%d", &year) != 1) /* error */;

The best way to get user input is to use fgets(), then, if needed, parse the input and assign to variables.

char tmp[1000];

printf("Insert the name of the author to search: ");
if (!fgets(tmp, sizeof tmp, stdin)) /* error */;
strcpy(author, tmp);

printf("Insert the year: ");
if (!fgets(tmp, sizeof tmp, stdin)) /* error */;
if (sscanf(tmp, "%d", &year) != 1) /* error */;

Otros consejos

you are trying to read input into author array where input length can be upto 300 characters,So i hope that you have declared your array size aschar author[301] , 300+1 (one extra for accomadating '\0').

You can use function like this scanf(" %300[^\n],author") this means keep reading characters from keyboard(or you can say keyboard buffer) until '\n' is found, and '\n' is generated when you hit Enter key,Hence we are forcing scanf() to read characters until we hit enter.

We can use fgets() but one of the problem of it is that it will even read '\n' into array,which will always print the output of next printf() operation on one extra new line.This can cause problem when you want your output to be in tabular form.

int main()
{
   char author[301]="\0";//initialize char array to '\0' NULL's
   int year;
   printf("Insert the name of the author to search: ");

   if( scanf(" %300[^\n]", author)!=1 )
   {
       printf("End of Input or Error Occurred reading Name.\n");
       return 1;// return (NON-ZERO) means unsuccessful termination
   }

   printf("Insert the year: ");
   if( scanf("%d", &year)!=1 )
   {
       printf("End of Input or Error Occurred reading Year.\n");
       return 1;// return (NON-ZERO) means unsuccessful termination
   }    
return 0;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top