Hi. When I run the following program....... and enter in for example 12345
why does it print out 2345. Where is 1 gone?
Code:int main () { int c; c = getchar(); while(c !=EOF) { c = getchar(); printf("%c", c); }
Hi. When I run the following program....... and enter in for example 12345
why does it print out 2345. Where is 1 gone?
Code:int main () { int c; c = getchar(); while(c !=EOF) { c = getchar(); printf("%c", c); }
You read it before the loop, but never printed it out. As such, you should swap the order of the two statements in the loop.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
I changed it a bit to this.........
However I get the following output.......Code:line[i] = getchar(); while(line[i] != EOF) { line[i] = getchar(); } for(i = 0; i < strlen(line); i++) { printf("%c",line[i]); }
Dۅ��r���5���2���ۅ�
after putting in ddfdf
What went wrong here?
ultimately what I want to do is take each input form the command line and put them into their own variable. At the moment I'm playing around with printf to see what is actually contained in the array.
What you hadwas almost entirely correct. The hintOriginally Posted by metrosis referring to the two bold lines.Originally Posted by laserlight
The first "getchar" before the while loop, of course, gets a char. Then you go in the while loop and overwrite it by immediately getting another char. What you want to do is get a char, enter the while loop, print the char, get another char, and loop. This is what the hint above is saying to do.
The problem you had above with the "printf" is that you're trying to print a "char[]", but it doesnt have a null terminating character ('\0'). When you pass a string to "printf", it will print all of the contents of the string, up until (and excluding) the null terminating character. If the string does not contain the null terminating character, it keeps printing until either it finds one or it segfaults. If the string isnt null terminated, then just printf a character ("%c"), or add the terminating character.
The best way to read the characters and printing in the stdout is the following.I did small changes in your code as follows.
Code:int main () { int c; while((c=getchar()) !=EOF) //reading the character from user and checks whether it isn't EOF printf("%c", c); //prints the character if it isn't EOF.Else,come out from the loop }
Your example is fundamentally the same as metros' first posted attempt, once the two statements that I mentioned are swapped.Originally Posted by vivekraj
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)