如何只阅读每行的第一个单词?

我已经做了很多简单的程序,但我只是试图从文本文件的每一行读出第一个单词到一个char word[30]

我试过了,但没有成功。 哦,每次我阅读它都要重用那个char。 (每次我阅读时都要列出一个有序列表)。

任何人都可以通过一种简单而“干净”的方式向我展示一种从文件中读取这种方式的方法吗?

 FILE *fp; char word[30]; fp = fopen("/myhome/Desktop/tp0_test.txt", "r"); if (fp == NULL) { printf("Erro ao abrir ficheiro!\n"); } else { while (!feof(fp)) { fscanf(fp,"%*[^\n]%s",word);//not working very well... printf("word read is: %s\n", word); strcpy(word,""); //is this correct? } } fclose(fp); 

例如,对于包含以下内容的文件:

 word1 word5 word2 kkk word3 1322 word4 synsfsdfs 

它只打印这个:

 word read is: word2 word read is: word3 word read is: word4 word read is: 

只需在格式字符串中交换转换规范即可

  // fscanf(fp,"%*[^\n]%s",word);//not working very well... fscanf(fp,"%s%*[^\n]",word); 

读取第一个单词并忽略其余单词,而不是忽略该行并读取第一个单词。


编辑一些解释

%s忽略空格,因此如果输入缓冲区有“四十二”,则scanf忽略第一个空格,将“四十”复制到目标,并将缓冲区放在“二”之前的空格处

%* [^ \ n]忽略换行符之前的所有内容,不包括换行符。 因此,包含“one \ n two”的缓冲区在scanf之后位于换行符处(就像它是“\ n two”)

 so ross$ expand < first.c #include  int main(void) { char line[1000], word[1000]; while(fgets(line, sizeof line, stdin) != NULL) { word[0] = '\0'; sscanf(line, " %s", word); printf("%s\n", word); } return 0; } so ross$ ./a.out < first.c #include int char while(fgets(line, word[0] sscanf(line, printf("%s\n", } return } 

更新:好的,这是一个只使用scanf()。 实际上,scanf不能很好地处理离散线,你可以通过将字缓冲区设置为与行缓冲区相同的大小来避免字缓冲区溢出的选项, 但是 ,它的价值是什么......


 so ross$ expand < first2.c #include  int main(void) { char word[1000]; for(;;) { if(feof(stdin) || scanf(" %s%*[^\n]", word) == EOF) break; printf("%s\n", word); } return 0; } so ross$ ./a.out < first2.c #include int char for(;;) if(feof(stdin) break; printf("%s\n", } return } 

看看这个, strtokfunction就是我们所需要的。 你可以告诉函数在哪里用参数分割字符串,比如strtok (singleLine," ,'(");这里每次看到空格时都会剪切” “”和“。 strtok (singleLine," ");或仅在白色空间。

  FILE *fPointer,*fWords,*fWordCopy; char singleLine[150]; fPointer= fopen("words.txt","r"); fWordCopy= fopen("wordscopy.txt","a"); char * pch; while(!feof(fPointer)) { fgets(singleLine,100,fPointer); pch = strtok (singleLine," ,'("); fprintf(fWordCopy,pch); fprintf(fWordCopy, "\n"); } fclose(fPointer); 

结果