I made a simple program to find words inside of strings and it works well but it can't find the last word in the string. Example: when I type in "Hello world", it will only pushback "Hello".
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
vector<char> Buffer2;
string temp;
vector<string> FinalString;
string UserInput;
void SeperateString() {
for (int x = 0; x < UserInput.size(); x ) {
temp.clear();
if (UserInput[x] == ' ') {
for (int x = 0; x < Buffer2.size(); x ) {
temp = temp Buffer2[x];
}
FinalString.push_back(temp);
Buffer2.clear();
} else {
Buffer2.push_back(UserInput[x]);
}
}
}
int main() {
getline(cin, UserInput);
SeperateString();
for (int x = 0; x < FinalString.size(); x ) {
cout << FinalString[x] << endl;
}
}
CodePudding user response:
This will probably be a better implementation for your code:
void SeperateString() {
istringstream ss(UserInput); // needs #include <sstream>
while (ss >> temp)
{
FinalString.push_back(temp);
}
}
istringstream
documentation,
stringstream
documentation.
If you want to stick to your code, at the end of the loop, just check if Buffer2
has characters or not:
for (int x = 0; x < UserInput.size(); x ) {
temp.clear();
if (UserInput[x] == ' ') {
for (int x = 0; x < Buffer2.size(); x ) {
temp = temp Buffer2[x];
}
FinalString.push_back(temp);
Buffer2.clear();
}
else {
Buffer2.push_back(UserInput[x]);
}
}
if (Buffer2.size() > 0)
{
temp.clear();
for (int x = 0; x < Buffer2.size(); x ) {
temp = temp Buffer2[x];
}
FinalString.push_back(temp);
}
CodePudding user response:
You need to handle the last word separately because it does not have a space after it.
void SeperateString() {
for (int x = 0; x <= UserInput.size(); x ) {
temp.clear();
if (UserInput[x] == ' ' || x == UserInput.size()) {
for (int y = 0; y < Buffer2.size(); y ) {
temp = temp Buffer2[y];
}
FinalString.push_back(temp);
Buffer2.clear();
}
else {
Buffer2.push_back(UserInput[x]);
}
}
}