[英]Why all the functions don't work at all?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char passage[5000][20];
int wordnum;
char *getword(int x);
void readTextFile() {
FILE *fp;
//char buffer;
fp = fopen("data.txt", "r");
int i=1,j=1;
while (fscanf(fp,"%c", &passage[i][j]) != EOF){
if (passage[i][j] == '.' || passage[i][j] == ',' || passage[i][j] == '!' || passage[i][j] == '?' || passage[i][j] == ' '|| passage[i][j] == ';'){
i++;
j=1;
}else{
j++;
}
}
fclose(fp);
wordnum = i;
}
int main(){
readTextFile();
int i;
for (i=0;i<20;i++){
char *word = getword(i);
if (strlen(word)<= 0)
break;
printf("%d\n", strcmp(word,"am"));
printf("word[%d]=%s", i, word);
printf("length = %i \n\n", strlen(word));
}
}
char *getword(int i){
static char s[20];
int j=0;
while (passage[i][j] != '\0'){
s[j]=passage[i][j];
j++;
}
s[j]='\0';
return s;
}
我已经编写了这个程序来从文本文件中读取一段,然后将整个段落放入2d数组中进行处理。 我正在使用的功能是通过2d数组的第一个索引获取任何单词,然后将该单词与某些单词进行比较并返回结果。
但是该程序没有显示任何内容,尽管我没有发现任何错误。
由于以下陈述:
int i=1,j=1;
第一个单词将全部为“ \\ 0”,所有后续单词的第一个字符均为“ \\ 0”。
这就是为什么什么都不打印的原因。
注意:此语句:
j=1;
应该:
j = 0;
因为,如注释中其他地方所述,C中的数组索引以0而不是1开头
可能这些行:
int i=1,j=1;
while (fscanf(fp,"%c", &passage[i][j]) != EOF){
是您直接祸患的根源; 您对getword的唯一调用的i为零,找到一个空的(在设置之前使用)段落。 堆栈溢出是否应该有一个“代码审查”部分?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.