我正在尝试读取文件每一行的最后一个单词。当文件中的行看起来像 2011/1/29,,0 ,1063
时,我可以获得所需的结果,但当文件中的行看起来像 2011/1/29 时,我无法获得所需的结果,夏天,0 ,1063
我以为我正在标记每个“,”,因此该行中的字符串不应该影响我的结果,但它确实如此。有人知道为什么吗?
#include <stdio.h>
#include <string.h>
int main (){
FILE* fp;
char tmpline[256];
char* separator2 =",";
char* words;
int i = 0;
fp = fopen("printer.txt", "r");
while (fgets(tmpline, 256, fp) != NULL){
printf(tmpline);
if (tmpline != NULL){
words = strtok(tmpline,separator2); //get first token
while (words != NULL) { /* walk through other tokens */
for (i=0; i<3; i++) {
if (i==2) {
printf( "papers: %s\n",words);
}
words= strtok(NULL, separator2);
}
}
}
}
fclose (fp);
return 0;
}
这是输出的一部分
// 2011/1/29,,0 ,1063
// papers: 1063
// 2011/1/31,,2 ,991
// papers: 991
// 2011/2/1,,3 ,1789
// papers: 1789
// 2011/2/2,spring,4 ,974
// papers: 4
// papers: (null)
// 2011/2/3,spring,5 ,1119
// papers: 5
// papers: (null)
// 2011/2/4,spring,6 ,617
最佳答案
这将存储指向每个有效 token 的指针。当您没有更多 token 时,请使用存储的 token 。我还添加了更多分隔符,以包含空格,原因之一是 fgets
保留了文件中的 newline
。
#include <stdio.h>
#include <string.h>
int main (void){ // correct signature
FILE* fp;
char tmpline[256];
char* separator2 =", \t\r\n"; // added more delimiters
char* words;
char *lastword; // previous valid token
fp = fopen("printer.txt", "r");
while (fgets(tmpline, 256, fp) != NULL) {
lastword = NULL;
words = strtok(tmpline,separator2); // get first token
while (words != NULL) { // walk through other tokens
lastword = words; // remeber previous token
words= strtok(NULL, separator2); // get next token
}
if(lastword != NULL) {
printf( "papers: %s\n", lastword);
}
}
fclose (fp);
return 0;
}
关于c - 如何使用 strtok 进行标记,无论该行中是否有字符串 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37663048/