0

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;
1

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

Comments

1
#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.

2 Comments

@EricChoi If you don't know about std::cin, then stop right now! Get a couple of beginners books and start over.
cin is the basic way to get input from the terminal in C++. It comes in the header <iostream>, and the std:: is necessary unless you put "using namespace std;" at the top of the program. Using cin >> x; will get input from the terminal up to the next whitespace and try converting that stream of characters into whatever type x is. It will throw an exception if it can't make the conversion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.