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;
Agaz Wani
  • 5,514
  • 8
  • 42
  • 62
  • Possible duplicate of https://stackoverflow.com/questions/236129/the-most-elegant-way-to-iterate-the-words-of-a-string – Galik Nov 26 '17 at 06:24

2 Answers2

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));
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
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.

  • @EricChoi If you don't know about `std::cin`, then *stop right now!* [Get a couple of beginners books](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and start over. – Some programmer dude Nov 26 '17 at 05:37
  • cin is the basic way to get input from the terminal in C++. It comes in the header , 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 – idontseethepoint Nov 26 '17 at 05:40