working in dos or linux? could it be your need "\n" at end?
views:
1366answers:
9More information is needed here, as timhon asked, which environment are you working under? Linux, Windows, Mac? Also, what text editor are you using which displays these extra spaces?
My guess is that your space isn't really a space. Run
od -hc out.txt
to double check that it is really a space.
The end of line chars are:
System Hex Value Type
Mac 0D 13 CR
DOS 0D 0A 13 10 CR LF
Unix 0A 10 LF
For a end of line on each system you can:
printf("%c", 13);
printf("%c%c", 13, 10);
printf("%c", 10);
You can use this like
printf("empty");
printf("%c", 10);
Wikipedia Newline article here.
Try removing the '\n' from your printf()
statements, and run the code again. If the output file looks like one long word (no spaces), then you know that the only thing being inserted after the text is that '\n'.
I assume that the editor you are using to read the out.txt file just makes it look like there is an extra space after the output.
If you are still unsure, you can write a quick program to read in out.txt and determine the ASCII code of each character.
First, the code sample you've given doesn't compile as o and d are not defined...
Second, you've probably got whitespace at the end of the line you're reading in from the input file. Try opening it in vi to see. Otherwise, you can call a trim function on each line prior to output and be done with it.
Good luck!
Make sure you're looking at the output of the program you expect; this has a syntax error (no ";" after int n
).
Okay, it's a little hard to figure this out, as the example program has numerous errors:
g++ -o example example.cc
example.cc: In function 'int main()':
example.cc:19: error: 'k' was not declared in this scope
example.cc:22: error: 'o' was not declared in this scope
example.cc:24: error: 'd' was not declared in this scope
make: *** [example] Error 1
But it's not going to be your input file; your scanf will be loading whatever you're typing into int
s. This example, though:
/* scan -- try scanf */
#include <stdio.h>
int main(){
int n ;
(void) scanf("%d",&n);
printf("%d\n", n);
return 0;
}
produced this result:
bash $ ./scan | od -c
42
0000000 4 2 \n
0000003
on Mac OS/X. Get us a copy of the code you're actually running, and the results of od -c.
I feel like it's not even close to this, but if you run this on Windows, you'll get \r\n as line terminators, and, maybe, under *nix, under a non-Windows-aware text editor, you'll get \r as a common blank space, since \r is not printable.
Long shot, the best way to test this is using an hexadecimal editor and see the file yourself.