tags:

views:

1061

answers:

5

When multiple scanf() statements are encountered in the code, then, except the first scanf() statement, all others are skipped, that is, there is no prompt for input for those scanf() statements when the code is run.

I have a tried a few suggestions. For eg, use of flushall() was suggested on some site, but that gives a compilation error.

Any help greatly appreciated. Thanks.

A: 

I've always thought scanf() was dangerous as it can leave your input streams in an indeterminate state.

I prefer to use other (safer) commands to bring in a string (fgets and such) then use sscanf to process it. Then you can always back up to the start of the string and restart.

paxdiablo
A: 

This sounds like some conversion issue. It may be that a %s conversion never ends or you specify a character which is never input or something like this. I suggest the following: a. Try something like: int a=0; int b=0; scanf("%d", &a); scanf("%d", &b); printf("a=%d, b=%d\n", a, b); If this works, try augmenting the conversions, to see which one causes the problem.

Yuval F
+3  A: 

Check the return value of scanf()!

From the man page: "scanf returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of a matching failure. Zero indicates that, while there was input available, no conversions were assigned; typically this is due to an invalid input character, such as an alphabetic character for a ‘%d’ conversion. The value EOF is returned if an input failure occurs before any conversion such as an end-of-file occurs. If an error or end-of-file occurs after conversion has begun, the number of conversions which were successfully completed is returned."

+2  A: 

An example of the code and input would definitely improve our ability to help you with your specific problem as there are a lot of potential situations that can cause the problem.

Example (I can think of quickly):

  • The format string does not match the next character on the input stream. The scanf is thus not reading anything.
  • The stdin input buffer is only flushed when full or return is encountered.
  • The input from 1 line of typing may be used by multiple scanf statements. Subsequent scanf statements pick up where the last on left off. Thus the program does not stop for user input.
  • The %s behaves differently on scanf and printf
    printf it prints a whole string.
    scanf it read ONE space separated word
Martin York
A: 

The Code simple, as it is:

#include <stdio.h>
int main()
{
long int z,s,n,i,j,m,x;
scanf("%ld ",&z);
for(i=0; i<z; i++)
  {
  scanf("%ld",&s); n=0;
  for (j=0; j<s; j++) { scanf("%ld",&m); n+=m; }
  x=n+s-1;
  printf("%ld\n",n);
  }
return 0;
}

Compilation:

D:\edycja>gcc WSEGA.c -o WSEGA.exe -Wall

D:\edycja>WSEGA.exe

D:\edycja> [Where was the program!?]
Michał