How to check if a string string string contains nothing in a string?

For example, when parsing a text file several times, this file has the following things:

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

Note that the 3rd line has an empty line (nothing or white spaces). The fact is that when you execute stringstream → laststring, and stringstream has an empty string (zero or just a space), it will not be overwritten by "laststring", it will not do anything. Anyway, to check it out in advance? I don't want to create a temporary empty string to check that it is still empty after stringstream -> it seems lame.

+5
source share
3 answers

- , , casting to bool false:

bool read = (ss >> laststring);

. ideone

+15

, - . , , , :

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

, , . , , , - std::getline() .

+1

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';
    }
}

iostream, fstream, sstream string.

0

All Articles