I'm sorry if this is a repeat question but I already tried to search for an answer and came up empty handed. So basically I just want to add strings (single words) to the back of a vector and then display the stored strings as a single string. I am quite the rookie.
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
int main(int a, char* b [])
{
vector<string> userString;
string word;
string sentence = "";
for (decltype(userString.size()) i = 0; i <= userString.size() - 1; i++)
{
cin >> word;
userString.push_back(word);
sentence += userString[i] + " ";
}
cout << sentence;
system("PAUSE");
return 0;
}
Why doesn't this work?
EDIT
int main(int a, char* b [])
{
cout << "Enter a sequence of words. Enter '.' \n";
vector<string> userString;
string word;
string sentence = ""; /
int wordCount = 0;
while (getline(cin, word))
{
if (word == ".")
{
break;
}
userString.push_back(word);
}
for (decltype(userString.size()) i = 0; i <= userString.size() - 1; i++)
{
sentence += userString[i] + " ";
wordCount += 1;
if (wordCount == 8)
{
sentence = sentence + "\n";
wordCount = 0;
}
}
cout << sentence << endl;
system("PAUSE");
return 0;
}
So my new program works. It just puts values at the back of a vector and prints them out 8 words to a line. I know there's easier ways but I'm just learning vectors and I'm going in baby steps. Thanks for the help guys.
Because userString is empty. You only declare it
vector<string> userString;
but never add anything, so the for loop won't even run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With