really? no warning about a semicolon?Code:printf("%d thousands", thousands);
really? no warning about a semicolon?Code:printf("%d thousands", thousands);
Hope this will give you some progressCode:#include <stdio.h> int main(void) { int a, b, c, thousands, hundreds, tens, ones; int ch; b=1000; printf("Enter a number(integer): "); scanf("%d", &a); thousands= a/b; printf("%d thousands\n", thousands); a = a%b; hundreds= a/100; printf("%d Hundreds", hundreds); while((ch = getchar()) != '\n' && ch != EOF); getchar(); return 0; } /* my outout Enter a number(integer): 9999 9 thousands 9 Hundreds */
ssharish2005
err... if it encounters EOF, then you read another char?Code:while((ch = getchar()) != '\n' && ch != EOF); getchar();
then you read another char (and don't store it) on an EOF'd file (stdin).
Last edited by robwhit; 09-07-2007 at 08:57 PM.
Okay, I don't know if you've managed to do it yet, so I've very quickly knocked up a solution. There are probably more efficient ways to do this, but I've tried to make the calculations as explanatory as possible, so you can understand what's going on. In the comments, I've also "assumed" a certain number, and explained on each line how the components of that number were deduced.
Output:Code:#include <stdio.h> int main(void) { int thou = 0; int hun = 0; int tens = 0; int units = 0; int number = 0; printf("Enter a number: "); scanf("%d", &number); //assume number = 4123 thou = number/1000; // thou now stores 4 tens = number%1000; // tens now stores 123 hun = tens/100; // hun now stores 1 units = tens%100; // tens is 123, so units stores 23 tens = units/10; // tens now stores 2 units = units%10; // units now stores 3 printf("\n\nThousands: %d", thou); printf("\nHundreds: %d", hun); printf("\nTens: %d", tens); printf("\nUnits: %d\n\n", units); }
Code:Enter a number: 1834 Thousands: 1 Hundreds: 8 Tens: 3 Units: 4
Last edited by osiris^; 09-08-2007 at 01:39 AM.
The main idea of that code is to clear the input buffer. So get the first remaining char in the buffer till it find '\n' or EOF. If any of these is found the loop breaks and comes out clearing the buffer.
If it encounter the EOF, ch != EOF, this become false. Hence the buffer clears.
ssharish2005
yes but it will only work if it encounters a newline before an EOF. the loop is fine, it is this line that's the problem:you'd be reading from stdin when you already reached the end of stdin. getchar() doesn't just pause the program. it reads and returns a character from stdin. if there are no more characters to be read, what do you think it is going to do?Code:getchar();
Last edited by robwhit; 09-08-2007 at 10:10 PM.