Archived

This topic is now archived and is closed to further replies.

Ledneh

scanf() / cin returning on no data?

Recommended Posts

Hi. I'm going to be taking part in a programming contest in a few weeks, and some of the test problems require input to end on blank data (just a return, no typing). However, both cin and scanf() refuse to return until I type in SOMETHING--and so there's no way for me to successfully complete the program, AFAIK. Is there anything I can do? Also, it seems they freak out somewhat at C++ I/O, so if you can answer in terms of C I/O functions, that'd be best. (edit) in other words, I want the program to keep accepting data until the user presses return on a blank line of data--we'll assume the user inputs valid data for now (/edit) -=-=-=-=-=-=-=- We are the Dyslexia of Borg. Futertility is resistant and your ass will be laminated. [edited by - Ledneh on October 16, 2003 1:51:14 PM]

Share this post


Link to post
Share on other sites
Hmm, yeah, I guess that'll work. As long as the function returns an empty string when I hit enter without any data. Thanks

[edited by - Ledneh on October 16, 2003 2:25:14 PM]

Share this post


Link to post
Share on other sites
can try doing a loop with kbhit() in the conio.h library... it goes until a key is pressed.. inside a looped couple with soemthing it could work well...



RanBlade
"Passion is what drives you to stay up until 4am fixing that bug that hardly anyone would notice...Passion is where great games come from, if you dont live and breathe games you shouldn''t be in the games industry." - Dave Pottinger, Ensemble Studios

[GameDev][C++ Page][Game Tutorials][FreeBSD][HawkNL(Hawk Network Library)][NeHe Productions][Mage Tower Ent-My Site]

Share this post


Link to post
Share on other sites
scanf() will not return until you hit enter when you are in interactive mode. However when a stdin is redirected to use a file (which is how the judges will execute your code -- I''m assuming ACM here) it''s a different story.

scanf() returns the number of variables it has correctly parsed, so for example scanf("%d",&num) will return 1 if it finds a number, 0 if it doesn''t find one and -1 if it hits EOF. This leads to loops that look something like this:

while (scanf("%d",&num)==1) { /* do stuff */ }

If you are going to be going the gets() route, gets() returns NULL when it encounters EOF. So the loop looks something like this:

while (gets(line)!=NULL) { /* do stuff */ }

Test this out yourself by executing the program from the command line as follows:

prog.exe <input.txt

Where input.txt has your problem input.

There are parallels for C++ input as well, but I don''t remember them .

Share this post


Link to post
Share on other sites