This is making no sense to me. I do something to the code and it works only the first time. I then test it again and it goes back to not including the last element in the vector. I have no idea what I am doing wrong. Please help.
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;
}
CodePudding user response:
If there is no space after the last word, you are not adding it to your vector.
CodePudding user response:
You are scanning the sentence
one letter at a time, appending each letter to word
until you encounter a space, and only then are you inserting the word
into the vector
. So, if the sentence
does not end with a space, the last word
won't be inserted into the vector
.
There are a few different ways you can fix that:
- check if
word
is not empty after the loop exits, and if not then insert it into the vector:
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;
}
- Scan for word boundaries yourself, such as with
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;
}
- put the
sentence
into astd::istringstream
and then useoperator>>
to extract complete whitespace-separate words from it. Let the standard library do all the heavy parsing for you:
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;
}