JimR
JimR

Reputation: 2225

Having trouble with the scanf() function

I'm fairly new to C but I'm having a bit of trouble writing a program that takes user input. This is the bit of code I'm having trouble with:

int xPos, yPos;    
while(1)
{
        printf("Enter two integers: ");
        if(scanf("%d %d", &xPos, &yPos) == 2)
        {
            printf("success \n");
        }
        else
        {
            printf("fail");
        }

}

Example run through of what I want as is follows:

Enter two integers: 4 4
success
Enter two integers: 13
fail
enter two integers: sda asd
fail

and it'll just keep going

But what I get is:

Enter two integers: 4 4
success
Enter two integers: 13
5 (it goes onto a new line for me and I have to enter something else to make it keep going) 
fail
Enter two integers: sda asd
Enter two integers:Enter two integers:Enter two integers:Enter two integers:Enter two integers:Enter two integers:Enter two integers:Enter two integers:Enter two integers:Enter two integers:Enter two integers: and on and on.. you get the idea.

Any hints as to what I'm doing wrong? I want it to scanf as soon as the enter button is hit.

Upvotes: 0

Views: 397

Answers (3)

wallyk
wallyk

Reputation: 57794

That is a weakness of scanf. Instead use fgets(buf, sizeof buf, stdin) to read a whole line as text and then use sscanf to try to extract values out of the line.

If the data is well behaved, gets() can also be used. But as someone rightly points out, the buffer used with gets() can easily lead to nasty buffer overruns.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 882416

That's because scanf will simply wait until you enter two integers (unless it gets an error or end of file). It doesn't care about the presence of newlines in this case, it will toss them away and wait for another integer.

If you want to process lines, you should use fgets to get a line and then sscanf that to extract the integers.

See this answer for a safe way to get lines from standard input. Beyond that, it only a small modification to turn your scanf (...) into sscanf (buffer, ...).

Upvotes: 1

codersarepeople
codersarepeople

Reputation: 2001

scanf('%d %d'...

keeps scanning the standard in until it sees the two integers it's looking for. One solution is to try taking in a string and then using atoi to find out if it's in the correct format, though it's possible there's a better solution.

Upvotes: 0

Related Questions