Reputation: 141
I have a string of non-uniform space separated integers ,I want to do some arithmetic operations on the elements so I have decided to first convert the string to integer array. Below is my approach:
string s; //let s="1 2 30 54 899 2 7 3 1";
cin>>s;
int n=s.length();
vector<int>arr(n);
for(int i=0;i<n;i++)
{
if(s[i]==' ')continue;
else{
arr.push_back(s[i]-'0');
}
}
for(int i=0;i<n;i++)
{
cout<<arr[i]<<endl; // arr should be{1,2,30,54,899,2,7,3,1};
}
What is wrong in this approach ?
Upvotes: 0
Views: 257
Reputation: 51766
What is wrong in this approach?
operator>>
only extracts until the first encountered character in std::cin
that satisfies std::isspace()
, so s
could not possibly be initialized to a string containing spaces in your program.n
should be the length of the array. The number of characters is not equal to the number of whitespace-separated values.arr
to length n
and then use push_back()
. You should be default initializing the vector so it starts empty.push_back()
each digit as a separate element.You can use std::getline()
to initialize the string from std::cin
and std::istringstream
to simplify extracting the formatted integers:
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
int main()
{
std::string s;
std::getline(std::cin, s);
std::istringstream iss(s);
std::vector<int> arr;
for (int i; iss >> i;) {
arr.push_back(i);
}
for(auto& v : arr)
{
std::cout << v << std::endl;
}
}
Upvotes: 2
Reputation: 1
You 'll loop all elements and convert with stoi
.
Then put it in the int-array.
Upvotes: 0