我已经彻底搜索了我的问题的答案,但没有太大的成功。我希望这里有人可以帮助我。 我有一个简单的代码,它从文件中读取 1 行并计算该行中的字符数和单词数。我使用空白字符来确定新单词何时开始,并使用\n 来确定该行何时结束。
出于某种原因,从未检测到空格,程序进入无限循环。 如果我将缓冲区初始化为\n,就会发生这种情况。如果我不这样做,即使是\n 也不会被检测到。
提前致谢。
memset(&buf[0], '\n', sizeof(buf));
read(fd, &buf[0], sizeof(buf));
while(buf[i] != '\n') {
while(buf[i] != ' ') {
no_of_chars++;
i++;
}
no_of_words++;
i++;
}
我正在阅读的文件内容:“这是一个测试文件” 编译器:GCC (Ubuntu)
最佳答案
有两个问题:
memset(&buf[0], '\n', sizeof(buf));
read(fd, &buf[0], sizeof(buf) - 1); /* else read could overwrite all your line feed chars */
while(buf[i] != '\n') {
while(buf[i] != ' ' && buf[i] != '\n') { /* else the inner while skips line feed chars */
no_of_chars++;
i++;
}
no_of_words++;
i++;
}
关于c++ - C 字符串 :\n & ' ' not detected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9677114/