gcc 4.4.4 c89
次のコードを使用して、fgetsを使用してファイルを読み込みます。MまたはFのいずれかの性別を取得したいだけです。
ただし、性別は常に文字列の最後の文字であるため。strlenを使えばキャラクターが手に入ると思いました。ただし、何らかの理由で、strlenとマイナス2を取得する必要があります。strlenにヌルが含まれていないことはわかっています。ただし、キャリッジリターンは含まれます。
私が読んでいるテキストの正確な行はこれです:
"Low, Lisa" 35 F
私のコード:
int read_char(FILE *fp)
{
#define STRING_SIZE 30
char temp[STRING_SIZE] = {0};
int len = 0;
fgets(temp, STRING_SIZE, fp);
if(temp == NULL) {
fprintf(stderr, "Text file corrupted\n");
return FALSE;
}
len = strlen(temp);
return temp[len - 2];
}
strlenは、16を返す必要があると感じたときに17を返します。キャリッジリターンを含む文字列の長さ。-2ではなく-1を実行する必要があると感じています。
あなたが私の質問を理解するならば、どんな提案でも。
ありがとう、
編集:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops
after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the
buffer
したがって、バッファには次のものが含まれます。
"Low, Lisa" 35 F\0\r
\ rが含まれている場合、strlenから17を返すのはどれですか?私はそれを考えるのは正しいですか?