Reputation: 91
I am trying something like this:
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int main()
{
string inputStr;
vector <string> strVector;
cin.getline(inputStr,200);
int i=0;
while (inputStr!=NULL){ //unless all data is read.
strVector[i]=getline(inputStr," ");
i++;
}//while.
for (int j=0; j<strVector.size(); j++){
cout<< strVector[j];
cout<<endl;
}
} //main.
Any one who can help. I am trying to store my input string in vector
string and then I can push_back my ith string.
Upvotes: 0
Views: 2533
Reputation: 8587
Here is nother way:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
vector<string> strVec;
string str;
cout<<"Enter # to quit \n\n";
int i=0;
while (str!="#")
{
cout<<"Input text No. "<<i+1 <<" here > ";
cin>>str ;
strVec.push_back(str);
i++;
}
cout<<"\nStored text\n----------\n";
for (int j=0; j<strVec.size()-1; j++) cout<<j+1<<" "<< strVec[j]<<"\n";
cout<<"\n\n";
return(0);
}
Upvotes: 0
Reputation: 103703
Much of your code involving inputString is invalid. There is no getline member of istream
that takes a std::string
, so this is invalid:
cin.getline(inputStr,200);
What you want there instead is the global getline:
getline(cin, inputStr);
Second, there is no global getline which reads directly from a std::string
, so this is invalid:
strVector[i]=getline(inputStr," ");
What you want to use there is an istringstream
. Altogether, your code might look something like this:
std::getline(std::cin, inputStr);
std::istringstream iss(inputStr);
std::string word;
// read from the istringstream until failure
while (std::getline(iss,word,' '))
strVector.push_back(word);
If you want to delimit on whitespace(including tabs) then you can use operator>>
instead of getline.
Upvotes: 3
Reputation: 17642
I think you are looking for the push_back
method of the std::vector
template
Upvotes: 1