Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets() includes the newline at the end [duplicate]

Tags:

c

string

fgets

fgets(input,sizeof(input),stdin);
if (strcmp(input, "quit") == 0){
  exit(-1);
}

If I type quit, it does not exit the program; I'm wondering why this is the case.

By the way input is declared as char *input;.

like image 732
Man Person Avatar asked Nov 18 '12 19:11

Man Person


People also ask

Does fgets include the newline?

The fgets() function stores the result in string and adds a NULL character (\0) to the end of the string. The string includes the newline character, if read.

What does fgets return at end-of-file?

RETURN VALUE Upon successful completion, fgets() returns s. If the stream is at end-of-file, the end-of-file indicator for the stream is set and fgets() returns a null pointer. If a read error occurs, the error indicator for the stream is set, fgets() returns a null pointer and sets errno to indicate the error.

Does fgets read newline C?

New! Save questions or answers and organize your favorite content.

How do I not add new line in fgets?

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.


2 Answers

The function fgets might add a newline at the end of the string read. You'll have to check that:

size_t ln = strlen(input) - 1;
if (input[ln] == '\n')
    input[ln] = '\0';

or even

strtok(input, "\n");
like image 131
codaddict Avatar answered Oct 29 '22 02:10

codaddict


Trailing newline in your input. See man fgets. Test for "quit" + newline, for example:

fgets(input,sizeof(input),stdin);
if(strcmp(input, "quit\n") == 0){
    exit(-1);
}

I completely missed the last sentence, re char *input. Depending on the architecture, input will be 4 or 8 bytes long. So the code is effectively

fgets(input, 8, stdin);

which doesn't reflect the real size of memory, input points to. This might "work" as long as the input is shorter than eight bytes, but will truncate the input, if it is larger. Furthermore, you will get the rest of the input the next time you call fgets.

You should either give the real size or take @JonathanLeffler's advice and declare a char array instead, e.g.

char input[64];
fgets(input, sizeof(input), stdin);

or

char *input = malloc(N);
fgets(input, N, stdin);
like image 31
Olaf Dietsche Avatar answered Oct 29 '22 03:10

Olaf Dietsche