0

I want to put a string with different data types into separate arrays, suppose I have the following string (In each line, each "field" is separated by a white space " ") :

string s = "1 2 3 Hello_world
            3 4 1 Hi_world   
            1 5 3 Bye_world"

I want to put this string into 4 separate arrays, each array is the values in each column so it will display something like this when displayed:

s[0] = 1, 3, 1
s[1] = 2, 4, 5  
s[2] = 3, 1, 3  
s[3] = Hello_world, Hi_world, Bye_world

How do I initialize and achieve these arrays? Other languages have a function called split (C#, PHP etc), what about C++?

Also, I can only use Arrays, not vector. Please someone advice. Thank you!

2 Answers2

0

Since you have a string, let's make it a stream:

std::istringstream input_stream(s);

The pattern seems to be that each row of the string will be the next element of your destination arrays.

int a[3];
int b[3];
int c[3];
std::string d[3];

int i;
int index = 0;
input_stream >> i;
a[index] = i;

input_stream >> i;
b[index] = i;

input_stream >> i;
c[index] = i;

std::string t;
input_stream >> t;
d[index] = t;

The above fragment is for one iteration.

A task for the OP is to convert the fragment into a loop to process each row of the string.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • I tried your method and tried placing it in a loop ... but it cannot compile and gives the following errors: cannot convert ‘std::string {aka std::basic_string}’ to ‘int’ in assignment a[counter] = s; b[counter] = s; c[counter] = s; Following are my codes: int a[14]; int b[14]; int c[14]; string d[14]; int counter = 0; istringstream inputStream(s); for(string t; inputStream >> t;) { a[counter] = t; b[counter] = t; c[counter] = t; d[counter] = t; counter++; } – HelloWorldSaveMe Aug 01 '18 at 04:34
  • for a more organized look of my codes. please refer to below. – HelloWorldSaveMe Aug 01 '18 at 04:35
  • Don't put code into comments; it becomes difficult to read. Edit your post with the new text. – Thomas Matthews Aug 01 '18 at 13:45
0

What you need is a Tokenizer routine that can split your string into substrings with your particular separators ("\n" in one case, and " " in the other). Then you can save your resulting substrings into a vector or strings (std::vector vectorOfStrings;)

Have a look at the answers here:

How do I tokenize a string in C++?

PlinyTheElder
  • 1,454
  • 1
  • 10
  • 15