Removing the " n" from a string read using fgets()

Asked

Viewed 7,954 times

8

Usually when using the fgets() function it reads the string but is sensitive to Enter, like reading the string to be adding to it the " n"??

5 answers

4

The function fgets() is similar to the function gets(), however, in addition to being able to read from a data file and include the new line character in the string, it also specifies the maximum size of the input string, the function gets() does not have this control, which could lead to "buffer overflow errors".

To remove the ' n' you can do as follows:

minhaString[strcspn(minhaString, "\n")] = 0;

Source.

  • And if the string has no ENTER (last line of a (incomplete) text file) this statement clears the whole string.

  • Does this only happen when working with file? I used this implementation to remove ENTER from fgets() when it receives keyboard value and worked, but I don’t know when this situation happens to clear the whole string if it doesn’t have ENTER.

  • Hmmm mistake my ... I was misinterpreting the strcspn(). strcspn("teste", "\n") return 5 and so your expression works well in all cases. Accept my apologies.

  • You don’t have to apologize to me quietly, your intention was good.

4

One thing you can do is read the string with the '\n' and delete it later by typing a ' 0' instead of the \n.

Another thing you can do is read the string letter by letter, via Getcha. So you have full control over what you write in your string.

4

The best way, in my opinion, is to read the full string and then remove the '\n'

char input[1000];
size_t len;
if (!fgets(input, sizeof input, stdin)) { /* tratamento de erro */ }
len = strlen(input);
if (len == 0) { /* normalmente isto nunca acontece */ }

/* alguns "ficheiros de texto" nao tem '\n' na ultima linha */
if (input[len - 1] == '\n') input[--len] = 0; // remove '\n' e actualiza len

1

1

Once read the String you can use String class methods. Ex.:

string teste;
FILE arquivo;
arquivo = fopen("arquivo.txt" , "r");
if( fgets (teste, [tamanho do arquivo], arquivo)!=NULL ) {
  puts(teste);
}
fclose(arquivo);
string testeSemN = teste.Replace("\n", String.Empty);
// ou também: teste.Replace("\n", "");
  • In C there are no classes, nor string, nor methods.

  • 1

    You’re right @pmg. I got the answer wrong. It applies to C# and not C... I found two functions as alternatives that might help. I have no way of testing now how they will behave with the " n". But the links are: http://creativeandcritical.net/str-replace-c/ and http://www.binarytides.com/str_replace-for-c/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.