Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Skipping scanf()

Status
Not open for further replies.

functziah

Programmer
Jul 15, 2002
6
US
My program keeps skipping scanf() functions. Instead of prompting the user for input it automatically inputs spacebar/10.

What am I doing wrong and how can I correct it?
 
Hi:

Just a guess, but it sounds like your buffer has extraneous garbage in it that scanf is interpreting as input.

I'd try putting a

fflush(stdin);

right before your scanf statement. Of course, this probably masks another problem somewhere in the program.

Regards,

Ed
 
Another possibility is that you might have missed the &. eg

scanf ("%d", &value);
 
Xwb:

Interesting; If I eliminate the address operator on my solaris 7 OS or Red Hat Linux 7.1 OS, it compiles and I can execute it; Of course, the answer is incorrect, but it doesn't skip the scanf.

Regards,

Ed
 
You can always check the return value of scanf() as well to make sure it read the proper number of values.

And as mentioned before, the '&' is important. If you are gathering a string, you don't need the '&' operator but you do for char, float, int, etc...

char sStr[30];
char cChar;
int iVal = 0;
int iRet;

if ((iRet=scanf("%s %d %c", sStr, &iVal, &cChar ))!= 3) {
/* then scanf() didn't get a proper read */
}

And, flushing stdin is ok to do as well. You probably are just getting the '\n' from a previous return in there.

Hope that helps.

-Tyler
 
Thanx

& has not been forgotten so that is not the problem.

Checking content is messy because the skippings occurs when I'm trying to reinput user data after checking for inappropriate input.

But fflushing the buffer has worked and it does seem the most appropriate in the circumstances.
 
I'm just guessing at which OS/Compiler you're using. Initial guess was VC++ on Windows: that is the only one I know of that skips. There is a bug in VC++ which appears to ignore the first line. Is it the first scanf that is being skipped or a random one in the middle? You could

getline (buffer, sizeof(buffer));
sscanf (buffer, ...)

That gets round the VC++ bug.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top