![]() |
| | #1 |
| Registered User Join Date: Dec 2008
Posts: 2
| scanf Code: int main(void){
int no, valid;
printf("\nHow many would you like?\n\n ");
if(scanf("%d",&no) != 1){ // Checking to see only one argument has been entered
printf("\nOnly one value.\n");
return (EXIT_FAILURE);
}
valid = scanf("%d",&no);
valid = ((valid != 0) && (valid != EOF));
if( !valid ){ // Checking to see the correct data type has been entered
printf("\nMust be an integer.\n");
return (EXIT_FAILURE);
}
return (EXIT_SUCCESS);
}
when I type in 'a 2 ' it prints 'Only one value' but when I type '2 a' it prints 'Must be an integer'. But in both instances I am expecting 'Only one value' to be printed. Sorry for such a trivial problem but any help would be much appreciated Cheers Last edited by Salem; 12-10-2008 at 11:39 AM. Reason: colour adds nothing, if it's all the same colour |
| cProgNoob is offline | |
| | #2 |
| Jack of many languages Join Date: Nov 2007 Location: Katy, Texas
Posts: 1,929
| When you enter '2 a', the first scanf() only sucks in the 2 and leaves the a in the input buffer because scanf() is smart enough (dumb enough?) to stop parsing at the first whitespace it encounters. So the 'a' is left for your second scanf() to pull.
__________________ Mac and Windows cross platform programmer. Ruby lover. Memorable Quotes From Recent Posts: I can't remember. |
| Dino is offline | |
| | #3 |
| Registered User Join Date: Dec 2008
Posts: 2
| thank u for such a prompt reply, it has been very helpful |
| cProgNoob is offline | |
| | #4 |
| Registered User Join Date: Dec 2008
Posts: 4
| You can use flushall(); after your first scanf so that it only reads the first scanf and removes the second one from the buffer. |
| haseth is offline | |
| | #5 | |
| C++ Witch Join Date: Oct 2003 Location: Singapore
Posts: 10,352
| Quote:
__________________ C + C++ Compiler: MinGW port of GCC Build + Version Control System: SCons + Bazaar Look up a C/C++ Reference and learn How To Ask Questions The Smart Way | |
| laserlight is offline | |
![]() |
| Tags |
| error, scanf |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| scanf() consideres useless | Snafuist | C Programming | 15 | 02-18-2009 08:35 AM |
| Help with a basic scanf procedure. | killpoppop | C Programming | 9 | 11-03-2008 04:39 PM |
| Odd data entry error, reading an unsigned integer with scanf | Xipher | C Programming | 2 | 02-20-2005 01:48 PM |
| Scanf and integer... | penny | C Programming | 3 | 04-24-2003 06:36 AM |
| scanf - data is "put back" - screws up next scanf | voltson | C Programming | 10 | 10-14-2002 04:34 AM |