简体   繁体   中英

keep doing scanf for all input in command line. C program

I am trying to get all the input from the command line and putting it in a linked list. the numbers from the command line are of this format 0-1 2-3 4-9 etcc Here is what I did to store a pair of numbers in two variables:

scanf("%d-%d", &a, &b);

Now, this scanf statement is inside a loop and my question is: what is the condition of the loop? I want to keep doing scanf until all the input is finished.

Thanks in advance.

A famous, if not notorious characteristic of scanf is that it will leave data in input buffer when reading non-string data(eg, int ). Check out here: Leave data in input buffer .

Try this:

do
{
  int x = scanf("%d-%d", &a, &b);
}while ((x != EOF) && (getchar() != '\n'));

You need to compare scanf output with EOF. And most importantly, you need flush out the '\\n' left by scanf in input buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM