本文介绍了如何知道输入流到达某行中的最后一个字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中从ifstream读取输入。输入是一串用分隔符分隔的单词,所以我正在阅读像word1 word2 word3作为流>> w1 >> w2 >> w3;我需要知道当我到达最后一句话,那么我该怎么办呢?词的数量是可变的,但它应该总是均匀的。

I'm reading input from an ifstream in C++. The input comes as a bunch of words separated by tabs, so I'm reading in something like "word1 word2 word3" as stream >> w1 >> w2 >> w3; I need to know when I've reached the final word in the line, so how would I go about that? The number of words is variable, but it should be always even. Also, will the last word contain the \n, or will the \n be the last word?

推荐答案

最简单的(和通常的)解决方案是使用
std :: getline 读取行,然后使用
std: :istringstream

The simplest (and usual) solution is to read lines usingstd::getline, and then parse the line usingstd::istringstream:

std::string line;
while ( std::getline( std::cin, line ) ) {
    std::istringstream s( line );
    std::vector<std::string> words;
    std::string word;
    while ( s >> word ) {
        words.push_back( word );
    }
    //  ...
}

这篇关于如何知道输入流到达某行中的最后一个字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 15:25