Converting string vector to integer vector
Hello :)
My goal is to allow the person to input a string of numbers like:
1 22 333 4444 55555 666666 7777777 88888888 999999999
and make a vector called ivec that would look like:
ivec.at(0) = 1
ivec.at(1) = 22
ivec.at(2) = 333
ivec.at(3) = 4444
ivec.at(4) = 55555
ivec.at(5) = 666666
ivec.at(6) = 7777777
ivec.at(7) = 88888888
ivec.at(8) = 999999999
How would I do this?
This is what I have so far (there's a conversion failure, but I hope the goal is clear enough):
Code:
//user is to provide the numbers
cout << "Numbers: " ;
//user now provides the numbers in string form
string str_version;
getline( cin , str_version );
//stringstream is made
stringstream ss(str_version);
//string version vector is made
vector<string> svec;
//the string-version numbers provided by the user are written into the vector
copy( istream_iterator<string>(ss) , istream_iterator<string>() , back_inserter(svec) );
//integer version vector is now made
vector<int> ivec;
//this is where the conversion fails, but, atoi() or some other function, would basically
//convert the string version of the number into an integer and input that at the same
//slot, only in ivec this time.
for (int i = 0 ; i < (sizeof(svec) - 1) ; i++)
{
ivec.at(i) = atoi(svec.at(i));
}
//if this worked, then operating between the numbers would be no problem,
//such as adding two together
cout << ivec.at(1) + ivec.at(2) << endl;
//closing statements
cin.clear();
cin.ignore( numeric_limits < streamsize > ::max(), '\n');
cin.get();
main();
The best method would directly copy the integers into the vector, rather than convert them from a string version (unfortunately I'm working with what I know).
Thanks for any input :)