因此,我需要解决一个问题,我必须从文件中读取单词,并且仍然能够识别单词是否位于行尾。例如:
This is a test file
I need to distinguish every word
and still be able to print out every words that are at the end of a line
我尝试使用:
while(scanf("%s", string) != EOF){
len = strlen(string);
if (string[len] == '\n'){
printf("%s is a word at the end of a line", string);
}
}
但似乎没有任何正常工作。
有人可以帮我吗?
编辑1:我尝试过
if (string[len-1] == '\n')
但是它却给出了单词的最后一个字符。例如,“ file”的单词string [len-1]为'e',即使该单词位于第1行的末尾
最佳答案
您的scanf
呼叫读取单词,每次返回一个单词。它会跳过空格和换行符,因此您无法查看其中一个单词来查看它是否位于行尾。您需要一种不同的方法。