I currently have this program that prints a text file on the console, but every line has an extra new line below it. if the text was
hello world
it would output hello
world
the code is this
#include <iostream> #include <stdio.h> #include <string.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { FILE* fp; char input[80], ch = 'a'; char key[] = "exit\n"; int q; fp = fopen("c:\\users\\kostas\\desktop\\original.txt", "r+"); while (!feof(fp)) { fgets(input, 80, fp); puts(input); } fclose(fp); return 0; }
Puts automatically adds a new line at the end of your message every time you use it. If you don't want a newline, then use print .
You can simply do if (fgets(Name, sizeof Name, stdin) == NULL) {} . Not sure why you would want to do this. The point of removing newlines isn't to null-terminate strings; it is to remove newlines. Replacing a \n with a \0 at the end of a string is a way of "removing" the newline.
The puts() function in C/C++ is used to write a line or string to the output( stdout ) stream. It prints the passed string with a newline and returns an integer value. The return value depends on the success of the writing procedure.
The fgets function reads characters from the stream stream up to and including a newline character and stores them in the string s , adding a null character to mark the end of the string.
Typically one would use fputs() instead of puts() to omit the newline. In your code, the
puts(input);
would become:
fputs(input, stdout);
puts()
adds the newline character by the library specification. You can use printf
instead, where you can control what gets printed with a format string:
printf("%s", input);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With