转到重复问题以了解如何将字符串拆分为单词,但您的方法实际上是正确的。实际的问题在于你如何读取输入之前试图分裂它:
string tempInput;
cin >> tempInput; // !!!
当您使用cin >> tempInput
,你只从输入,而不是整个文本获得的第一个字。有工作你的出路是两种可能的方式,其中最简单的是忘掉了stringstream
,并直接迭代输入:
std::string tempInput;
std::vector<std::string> tokens;
while (std::cin >> tempInput) {
tokens.push_back(tempInput);
}
// alternatively, including algorithm and iterator headers:
std::vector<std::string> tokens;
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::back_inserter(tokens));
这种方法会给你输入的所有的标记在一个单一的矢量。如果您需要与各行的工作separatedly那么你应该使用getline
从<string>
头,而不是cin >> tempInput
:
std::string tempInput;
while (getline(std::cin, tempInput)) { // read line
// tokenize the line, possibly with your own code or
// any answer in the 'duplicate' question
}
不是一个真正的欺骗。这是“我在哪里犯错误”vs“什么是......的最佳方式”? – 2010-04-28 08:20:30
虽然问题是完全一样的:如何分割一个字符串,我相信@pmr提到的问题处理通用问题,而在这个问题中,问题不在于实际分裂 – 2010-04-28 08:21:28
@David @SF是的,你是对的。不幸的是,大多数答案不会以这种方式处理问题。 – pmr 2010-04-28 08:29:53