C
C
cromvwell2020-05-03 16:32:27
C++ / C#
cromvwell, 2020-05-03 16:32:27

How to enter a string without a line terminator?

#include <stdio.h>

int main()
{
    char country[64] = "", city[16] = "";
    fgets(country, 64, stdin);
    fgets(city, 16, stdin);
    printf("The capital of the state of %s is the city of %s", country, city);
    return 0;
}


Why is enter written at the end of the line when typing with fgets, if this function just means typing everything up to enter?

Russia
Moscow
The capital of the state of Russia
is the city of Moscow


...Program finished with exit code 0
Press ENTER to exit console.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
15432, 2020-05-03
@cromvwell

Well, yes, that's right:

The fgets() function reads up to num-1 characters from stream and puts them into the character array pointed to by str. Characters are read until a newline, EOF, or the specified limit is reached. At the end of the reading, the null character is placed in the str array immediately after the last read character. The "newline" character on reading will be preserved and become part of the str array.

But gets does not preserve the end of the line:
The gets() function reads characters from stdin and puts them into the character array pointed to by str. Characters are read until a newline or EOF is encountered. The "newline" character is not made part of the string, but is translated into the null character that terminates the string.

but it is not safe because there is no limit on the size of the input.
you can just trim the last character:
country[strlen(country)-1] = 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question