Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C puts() without newline

Tags:

c

file

newline

puts

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; } 
like image 206
Constantine Avatar asked Jun 21 '13 15:06

Constantine


People also ask

Does puts add a newline?

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 .

How do I make fgets not read newline?

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.

How does puts work in C?

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.

Does fgets add newline?

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.


2 Answers

Typically one would use fputs() instead of puts() to omit the newline. In your code, the

puts(input); 

would become:

fputs(input, stdout); 
like image 120
Alex North-Keys Avatar answered Sep 20 '22 02:09

Alex North-Keys


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); 
like image 24
Sergey Kalinichenko Avatar answered Sep 18 '22 02:09

Sergey Kalinichenko