C 如何使用if语句选择要显示的不同单词?
每当我将ch[index]==0时,它会给我文本文件中的第一个单词,但每当我选择ch[index]==1时,它什么也不给我。如何使这个if语句起作用C 如何使用if语句选择要显示的不同单词?,c,function,if-statement,C,Function,If Statement,每当我将ch[index]==0时,它会给我文本文件中的第一个单词,但每当我选择ch[index]==1时,它什么也不给我。如何使这个if语句起作用 #include <stdio.h> #include<stdlib.h> int main(){ FILE * fr = fopen("/home/bilal/Documents/file.txt","r"); char ch[100]; int index = 0; if(fr !=
#include <stdio.h>
#include<stdlib.h>
int main(){
FILE * fr = fopen("/home/bilal/Documents/file.txt","r");
char ch[100];
int index = 0;
if(fr != NULL){
while((ch[index] = fgetc(fr)) != EOF){
if(index[ch]==1){ // here is if statement
if(ch[index] == ' ') {
ch[index] = '\0';
printf("Here is your %s: \n",ch);
index = 0;
}
else { index++; }
}
}
fclose(fr);
}
else{ printf("Unable to read file."); }
return 0;
}
下面是一段代码,它应该可以工作并显示第二个单词,尽管我没有测试它:
#include <stdio.h>
//#include <stdlib.h> //not needed
int main(void)
{
FILE* fr = fopen("/home/bilal/Documents/file.txt", "r");
char ch[100];
int index = 0, c, i = 0;
//for loop is useless
if (fr == NULL)
{
printf("Unable to read file.");
return 0;
//I prefer error checking without a giant if statement, but it's up to you
}
c = fgetc(fr); //fgetc() returns an int, not char
while (c != EOF)
{
ch[index] = c;
if (ch[index] == ' ')
{
if (i == 1)
{
ch[index] = '\0';
printf("Here is your string: %s\n", ch); //The format seemed weird to me, that's why I changed it, use what you need
}
index = 0;
i++;
}
else
index++;
c = fgetc(fr);
}
fclose(fr);
//return 0; //not needed in C99 or later
}
首先,在i循环中有一个fclosefr,但之后就再也不会打开该文件了。您还在循环中第二次增加i,这在实践中是不好的
试试这个:
for (int i=0; i<8; i++){
fr = fopen("/home/bilal/Documents/file.txt","r");
index = 0;
if(fr != NULL){
然后从顶部拆下fopen
可能有比在每次循环迭代时打开和关闭文件更好的方法。为什么具体地说我<8?for循环是无用的,你也可以删除它。因此,请注意,while是一个无限循环。ch[index]是一个字符,但EOF是一个字符范围之外的整数,它永远不会比较为真。在删除for循环后,它仍然不起作用。OP试图修改该问题以删除无用的for循环,但在代码中又注入了一些错误。看看我的答案。现在问题在我回答的时候变了。