Reputation: 23
I'm just started learning c++. In Java, to split an input, you would just to have to use the split method to split the spaces from an input. Is there any other simple way, where you can split a string input in an integer array? I don't care about efficiency; I just want some codes that could help me understand how to split spaces from an input.
An example would be: Input: 1 2 3 4 Code:
int list[4];
list[0]=1;
list[1]=2;
list[2]=3;
list[3]=4;
Upvotes: 0
Views: 547
Reputation: 409146
In C++ this can be handles with basically a single function call as well.
For example like this:
std::string input = "1 2 3 4"; // The string we should "split"
std::vector<int> output; // Vector to contain the results of the "split"
std::istringstream istr(input); // Temporary string stream to "read" from
std::copy(std::istream_iterator<int>(istr),
std::istream_iterator<int>(),
std::back_inserter(output));
References:
If the input is not already in a string, but is to be read directly from standard input std::cin
it's even simpler (since you don't need the temporary string stream):
std::vector<int> output; // Vector to contain the results of the "split"
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(output));
Upvotes: 2
Reputation: 483
#include <iostream>
#include <array>
int main()
{
int list[4];
for (int i=0; i<4; ++i)
{
std::cin >> list[i];
}
std::cout << "list: " << list[0] << ", " << list[1] << ", " << list[2] << ", " << list[3] << "\n";
return 0;
}
This will split the input on whitespace and assumes there are at least 4 ints in the input.
Upvotes: 1