這對我來說毫無意義。我對代碼做了一些事情,它只在第一次作業。然后我再次測驗它,它回傳到不包括向量中的最后一個元素。我不知道我做錯了什么。請幫忙。
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;
}
uj5u.com熱心網友回復:
如果最后一個單詞后沒有空格,則不會將其添加到向量中。
uj5u.com熱心網友回復:
要掃描的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放入 a 中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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/341799.html
標籤:C
