C++读取文件忽略前导空白,实现NextWord函数的问题
解决C++中读取文本时跳过任意空白获取单词的问题
你的问题核心在于getline指定单个空格作为分隔符的行为不符合需求——它只会在遇到单个空格时截断,不会自动跳过连续的空白字符(包括多个空格、换行符),所以才会把中间的空白当成"单词"返回。下面给你两种简单有效的解决方案:
方案一:利用标准输入流的默认行为(最简洁)
C++的std::istream提供的>>运算符天生就支持跳过所有前导空白字符(空格、换行、制表符等),然后读取直到下一个空白字符为止,完美匹配你对"单词"的定义。修改你的NextWord函数如下:
#include <fstream> #include <string> #include <iostream> std::string NextWord(std::ifstream& inputStream) { std::string nextWord; // >> 自动跳过所有空白,读取连续非空白字符作为单词 inputStream >> nextWord; return nextWord; } int main() { std::string input = "input.txt"; std::ifstream inFile(input); if (!inFile.is_open()) { // 建议增加文件打开失败的判断 std::cerr << "Failed to open file!" << std::endl; return 1; } std::cout << NextWord(inFile) << std::endl; std::cout << NextWord(inFile) << std::endl; std::cout << NextWord(inFile) << std::endl; return 0; }
假设你的input.txt内容是:
ABC DEF GH IJK
运行程序会输出:
ABC DEF GH
完全符合你的预期。
方案二:手动处理空白字符(自定义性更强)
如果你需要更灵活地控制空白字符的判断逻辑(比如自定义哪些字符算空白),可以手动跳过空白再读取单词:
#include <fstream> #include <string> #include <iostream> #include <cctype> // 用于std::isspace std::string NextWord(std::ifstream& inputStream) { std::string nextWord; char c; // 跳过所有前导空白字符 while (inputStream.get(c) && std::isspace(static_cast<unsigned char>(c))) { // 仅跳过,不做其他操作 } // 如果流未结束,读取直到下一个空白字符 if (inputStream) { do { nextWord += c; } while (inputStream.get(c) && !std::isspace(static_cast<unsigned char>(c))); } return nextWord; } // main函数同方案一
这个方法通过逐个字符读取,先跳过所有空白,再收集非空白字符,直到遇到下一个空白,同样能实现你的需求。
为什么原代码会出问题?
原代码中getline(inputStream, nextWord, ' ')的逻辑是:从流中读取字符,直到遇到单个空格' '为止,把读取到的内容(包括中间的其他空白)存入nextWord。比如对于ABC DEF,第一次调用会得到ABC,第二次调用会读到两个空格(因为第一个空格是分隔符,接下来的两个空格会被当成内容读取,直到下一个空格),这就是你看到的"不断读取空白字符"的原因——它不会自动跳过前导空白,只会严格按照指定的单个分隔符截断。
内容的提问来源于stack exchange,提问作者Reno
相关产品推荐
相关产品推荐

