Reputation: 111
I am using
string temp ;
vector <int> arr ;
while(getline(cin,temp,' '))
{
arr.push_back(temp);
}
but it's not working as I expected and I am getting a compile time error
no matching function for call to 'std::vector<int>::push_back(std::string&)'|
Please provide a solution in C++ or C
Upvotes: 1
Views: 737
Reputation: 236
You probably want to read the line as a string first, then separate the integers and afterwards push them into the array.
C++11 (I think?) solution:
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <sstream>
int main()
{
std::vector<int> arr;
for (std::string temp; std::getline(std::cin, temp); )
{
std::istringstream iss(temp);
std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::back_inserter(arr));
for (const auto & elem : arr)
std::cout << elem << ' ';
std::cout << '\n';
arr.clear();
}
return 0;
}
Problem is you now need a way to stop the infinte loop, but that can be easily solved with a simple condition. It's up to you.
Upvotes: 0
Reputation: 625
This takes advantage of std::stoi
which is part of the C++11 standard. stoi
simply takes a string representation of an integer and turns it into its integer form. i.e. "123" -> 123
.
string temp ;
vector <int> arr ;
while(getline(cin,temp,' '))
{
arr.push_back(stoi(temp));
}
Upvotes: 3
Reputation: 11353
You have almost got it right, but your vector type is wrong, you are storing strings, not integers.
string temp;
vector<string> arr;
while(getline(cin,temp,' '))
{
arr.push_back(temp);
}
Upvotes: 1