Removing the "\ n" of a string read using fgets ()

8

Generally when using the function fgets () it reads the string but is sensitive to Enter, how to read the string being to add the "\ n" ??

    
asked by anonymous 16.09.2014 / 00:31

5 answers

4

One thing you can do is read the string with '\n' and then delete it by typing a '\ 0' instead of \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.

    
16.09.2014 / 00:38
4

The best way, in my opinion, is to read the entire string and then remove '\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
    
16.09.2014 / 10:15
2

The fgets() function is similar to the gets() function, but besides being able to read from a data file and include the newline character in the string, it still specifies the maximum length of the string. gets() function does not have this control, which could lead to "buffer overflow" errors.

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

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

Font .

    
23.10.2015 / 00:07
1

To remove the '\ n' from the end of the string, try this:

size_t ln = strlen(input) - 1;
if (name[ln] == '\n')
    name[ln] = '
char *pos;
if ((pos=strchr(input, '\n')) != NULL)
    *pos = '
size_t ln = strlen(input) - 1;
if (name[ln] == '\n')
    name[ln] = '
char *pos;
if ((pos=strchr(input, '\n')) != NULL)
    *pos = '%pre%';
';
';
';

Source: link

or this:

%pre%

Source: link

    
16.09.2014 / 00:52
1

Once you read the String you can use methods of the String class. 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", "");
    
18.09.2014 / 02:17