我正在使用 fgets 从文件中读取以下行:
#C一二三四五六七八九十十一
每个单词(#C 除外)都是一个列标题。所以我的文件中有十一列。
我的目标是将这一行分成每个单词的记号。另外,我需要计算一下有 11 个列标题。 (列标题可以多于或少于 11 个)
我的问题是这一行末尾的空格。这是我正在使用的代码:
while(1){
fgets(buffer,1024,filename);
if (buffer[1] == 'C'){
char* str = buffer+2;
char* pch;
pch = strtok(str," ");
while(pch != NULL){
pch = strtok (NULL, " ");
if (pch == NULL)break; //without this, ncol contains +1 the
//amount of columns.
ncol++;
}
break;
}
}
此代码给我 ncol = 11。并且工作正常。(请注意,我正在阅读的行末尾有一个空格)
但是,如果我在行尾没有空格,那么它会给出 ncol = 10 并且不会读取最后一列。
我的目标是让 ncol =11 而不管 not 末尾是否有空格。我只想读最后一个单词,检查是否还有更多单词,如果没有,则退出。
最佳答案
如果你改变这个循环:
while(pch != NULL){
pch = strtok (NULL, " ");
if (pch == NULL)break; //without this, ncol contains +1 the
//amount of columns.
ncol++;
}
到:
while(pch != NULL){
char *keep = pch;
pch = strtok (NULL, " ");
if (pch == NULL)
{
if (strlen(keep))
{
ncol++;
}
break; //without this, ncol contains +1 the
}
//amount of columns.
ncol++;
}
因此,如果字符串中还剩下一些东西,当 pch
为 NULL 时,您就有了另一个字符串,因此在 if 中增加 ncol
。 [您可能会发现,如果输入文件格式不正确,则 if (strlen(keep))
需要更彻底,但我假设您的输入是“nice”]
关于c++ - 在一行中的最后一个单词后立即退出 While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16340991/