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" ??
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" ??
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.
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
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 .
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
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", "");