我正在从 C++ 中的 ifstream 读取输入。输入是一堆由制表符分隔的单词,所以我正在读取类似“word1 word2 word3”之类的内容作为流 >> w1 >> w2 >> w3; 我需要知道我什么时候到达了最后一个字,那我该怎么做呢?单词的数量是可变的,但应该始终是偶数。另外,最后一个单词会包含\n,还是\n 是最后一个单词?
问问题
1021 次
3 回答
8
最简单(也是通常)的解决方案是使用 读取行
std::getline
,然后使用 解析行
std::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 );
}
// ...
}
于 2013-07-31T18:49:10.847 回答
3
使用'读取ifstream
并将其推送到向量,如下所示:algorithm
std::copy
std::ifstream stream("input.txt");
std::vector<std::string> vec;
//replace stream with std::cin for reading from console
std::copy(std::istream_iterator<std::string>(stream),
std::istream_iterator<std::string>(),
std::back_inserter(vec));
这需要一个 EOF 来终止。Ctrl+Z或Ctrl+D依赖于Windows或Linux。
按照建议,您可以使用 C++11 的初始化列表,如下所示:
std::vector<std::string> vec{std::istream_iterator<std::string>{stream},
std::istream_iterator<std::string>{}};
于 2013-07-31T18:57:55.467 回答
1
我会建议mmap()
该文件。之后,您将整个文件放在您的虚拟地址空间中,并且可以像一大堆字符一样随意检查它。特别是对于这样的操作,你必须返回几个步骤,这是最合适的方法。作为额外的奖励,它也是最快的......
于 2013-07-31T19:00:45.893 回答