-2

I know there is questions dealing with skipping inputs for fgets(); however i have not found any help with this problem online or asking friends around.

I use:

fgets(tdataMplMsgStrng0_au8, 100, fpread);

to read a string from a text file and assign it to the string tdataMplMsgStrng0_au8. I have many fgets() before and after this and none are skipping data; however the others are all are converted to integers afterwards, like below:

fgets(temp_s32, 100, fpread);
sint32 tCILXIOD_dataMplMsgDisp4To0_u32 = atoi(temp_s32);

The problem is when i print this string to a text file it skips an extra line (besides the \n) that none of the others in the same format do:

fprintf(fp, "%s\n", tdataMplMsgStrng0_au8);

I printed each character in the string and noticed it has a "skipped line" as the character for the last char. I also see a char, 14 and onward, that i am not familiar with.

The code to print to command window:

    for (int i = 0; i < 100; i++)
    {
        printf("\n String[%d]: '%c'", i, tdataMplMsgStrng0_au8[i]);
    }

The output on the command window (Note the text file contains "0jkhjkhkkljh" for the line that sets tdataMplMsgStrng0_au8):

String[0]: '0'
String[1]: 'j'
String[2]: 'k'
String[3]: 'h'
String[4]: 'j'
String[5]: 'k'
String[6]: 'h'
String[7]: 'k'
String[8]: 'k'
String[9]: 'l'
String[10]: 'j'
String[11]: 'h'
String[12]: '
'
String[13]: ' '
String[14]: '|['
String[15]: '|['
String[16]: '|['

Any help understanding why the "skipping line" char in index 12 is there would be supper helpful. Also just for extra info, it would be nice to know why '|[' is there when i did not enter.

Scott
  • 135
  • 2
  • 9
  • You don't seem to be taking account of the actual string length read - the loop is for the array length, not the string length. Also be aware that `fgets` retains the newline at the end of the input, in the string. – Weather Vane Jun 29 '17 at 15:31

1 Answers1

2

fgets char * fgets ( char * str, int num, FILE * stream ); Get string from stream Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

Its' in the specs.

http://www.cplusplus.com/reference/cstdio/fgets/

Vlad Dinev
  • 432
  • 2
  • 9