7

例如,在解析文本文件时,有时该文件包含以下内容:

keyword a string here
keyword another string
keyword 
keyword again a string

请注意,第 3 行有一个空字符串(无或空格)。问题是,当您执行 stringstream>>laststring 时,并且 stringstream 有一个空字符串(null 或只有空格),它不会覆盖“laststring ",它什么也做不了。无论如何要事先检查这种情况吗?我不想创建一个临时空字符串只是为了检查它在 stringstream>> 之后仍然是空的,看起来很蹩脚。

4

4 回答 4

22

当您无法从流中读取时 - 它的状态会发生变化,因此当转换为 bool 时,它会返回 false:

bool read = static_cast<bool>(ss >> laststring);

或 - 在if-expr

if (ss >> laststring) 
    cout << "Just read: " << laststring;

查看示例

于 2012-10-16T22:08:15.073 回答
2

你只能在尝试阅读是否有东西之后才能知道。您可以做的是跳过空格并查看下一个位置是否有非空格:

if ((in >> std::ws).peek() != std::char_traits<char>::eof()) {
    ...
}

鉴于创建空字符串的成本很低,我不会费心尝试读取字符串。但是请注意,从流中读取不是基于行的,即在您上面的情况下,您需要先拆分行或使用类似std::getline()读取行的第二部分的东西。

于 2012-10-16T22:10:14.380 回答
0

您可以使用 getline 从文件中读取一行。然后,将该行复制到字符串流中,并一次从字符串流中读取一个单词。当流用完行/字时,流将自动停止阅读。

// open file
std::ifstream fin("text.txt");

// 'iterate' through all the lines in the file
unsigned lineCount = 1;
std::string line;
while (std::getline(fin, line))
{
    // print the line number for debugging
    std::cout << "Line " << lineCount << '\n';

    // copy line into another stream
    std::stringstream lineStream(line);

    // 'iterate' through all the words in the line
    unsigned wordCount = 1;
    std::string word;
    while (lineStream >> word)
    {
        // print the words for debugging
        std::cout << '\t' << wordCount++ << ' ' << word << '\n';
    }
}

您需要包括iostreamfstream和。sstreamstring

于 2012-10-16T22:18:35.357 回答
0

要检查字符串是否为空,请使用foo.size() == 0.

用于检查字符串流是否为空fooStream.rdbuf()->in_avail() == 0

于 2020-11-20T17:38:45.297 回答