C 如何返回要从文件中读取的结果?
在这段代码中,我试图返回C 如何返回要从文件中读取的结果?,c,return,C,Return,在这段代码中,我试图返回read函数中的值,并在main函数中打印其中一个值,但它没有返回。相反,它没有给我结果,只是空的结果。虽然我使用了printf来打印read函数中的数据,但它仍在工作,但使用return时,它不工作 #include <stdio.h> #include <stdlib.h> #include <string.h> #define STRING_LEN 200 char *wordOne = NULL, *wordTwo = NUL
read
函数中的值,并在main函数中打印其中一个值,但它没有返回。相反,它没有给我结果,只是空的结果。虽然我使用了printf
来打印read函数中的数据,但它仍在工作,但使用return时,它不工作
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_LEN 200
char *wordOne = NULL, *wordTwo = NULL, *wordThree = NULL, *wordFour = NULL, *wordFive = NULL;
int read(FILE *fname, char *findPin){
char string[STRING_LEN];
char * line = NULL, *pinFound = NULL;
while(fgets(string, STRING_LEN, fname)){
line = strtok(string, "\n");
pinFound = strstr(line, findPin);
wordOne = strtok(line, ",");
wordTwo = strtok(NULL, ",");
wordThree = strtok(NULL, ",");
wordFour = strtok(NULL, ",");
wordFive = strtok(NULL, ",");
if(pinFound)
return wordOne, wordTwo, wordThree, wordFour, wordFive; // problem in returning
}
}
int main(){
char pinFind[STRING_LEN];
FILE * fp1 = fopen("file.csv", "r");
printf("Enter the pin code: ");
scanf("%s", pinFind);
read(fp1, pinFind);
printf("%s\n", wordTwo);
return 0;
}
#包括
#包括
#包括
#定义字符串\u LEN 200
char*wordOne=NULL,*wordTwo=NULL,*wordThree=NULL,*wordFour=NULL,*wordFive=NULL;
int读取(文件*fname,字符*findPin){
字符字符串[string_LEN];
char*line=NULL,*pinFound=NULL;
while(fgets(string,string_LEN,fname)){
line=strtok(字符串“\n”);
pinFound=strstrstr(行,findPin);
wordOne=strtok(行“,”);
wordTwo=strtok(NULL,“”,“”);
wordThree=strtok(空,“,”);
wordFour=strtok(NULL,“”,“”);
wordFive=strtok(空,“,”);
如果(找到)
返回wordOne、wordTwo、wordThree、wordFour、wordFive;//返回时出现问题
}
}
int main(){
char pinFind[STRING_LEN];
FILE*fp1=fopen(“FILE.csv”,“r”);
printf(“输入pin码:”);
scanf(“%s”,pinFind);
读取(fp1,pinFind);
printf(“%s\n”,第二个字);
返回0;
}
有些实现的库中提供了一个read()
函数。最好使用不同的名称。此外,函数并不总是返回值,当返回值时,调用方将忽略该值。还要注意,您只能返回一个值:返回wordOne、wordTwo、wordThree、wordFour、wordFive代码>将返回单词5代码>可能是因为找不到pin,您没有在while循环或if语句之外的else或任何return语句。@WeatherVane我更改了名称,但结果仍然为空。@FivePlyPaper数据存在于文件中,当我打印而不是返回时,它会显示数据。请参阅。尽管您没有直接这样做,但通过strok()
获得的指针指向一个不再存在的字符串。