[英]My vector prints all elements but last one c++
这对我来说毫无意义。 我对代码做了一些事情,它只在第一次工作。 然后我再次测试它,它返回到不包括向量中的最后一个元素。 我不知道我做错了什么。 请帮忙。
cout << "Enter a sentence: " << endl;
getline(cin, sentence);
for (auto x : sentence) // stores individual words in the vector
{
if (x == ' ')
{
myString.push_back(word);
cout << word << endl;
word = " ";
}
else
{
word = word + x;
}
}
for (auto elem : myString)
{
cout << elem << endl;
}
如果最后一个单词后没有空格,则不会将其添加到向量中。
要扫描的sentence
一个字母的时间,每个附加信word
,直到你遇到一个空间,只有这样,你插入word
入vector
。 因此,如果sentence
不以空格结尾,则不会将最后一个word
插入到vector
。
有几种不同的方法可以解决这个问题:
word
是否为空,如果不是则将其插入向量中:cout << "Enter a sentence: " << endl;
getline(cin, sentence);
for (auto x : sentence)
{
if (isspace(static_cast<unsigned char>(x))
{
if (!word.empty())
{
myString.push_back(word);
word = "";
}
}
else
{
word += x;
}
}
if (!word.empty())
{
myString.push_back(word);
}
for (const auto &elem : myString)
{
cout << elem << endl;
}
string::find_first_(not_)of()
:cout << "Enter a sentence: " << endl;
getline(cin, sentence);
const char* wspace = " \f\n\r\t\v";
size_t start = 0, end;
while ((start = sentence.find_first_not_of(wspace, start)) != string::npos)
{
end = sentence.find_first_of(wspace, start + 1));
if (end == string::npos)
{
myString.push_back(sentence.substr(start));
break;
}
myString.push_back(sentence.substr(start, end-start));
start = end + 1;
}
for (const auto &elem : myString)
{
cout << elem << endl;
}
sentence
放入std::istringstream
,然后使用operator>>
从中提取完整的空格分隔词。 让标准库为您完成所有繁重的解析工作:cout << "Enter a sentence: " << endl;
getline(cin, sentence);
istringstream iss(sentence);
while (iss >> word)
{
myString.push_back(word);
}
for (const auto &elem : myString)
{
cout << elem << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.