String splitting problem

I want to split my string by every space. I have e.g. string array[14] as "12343212 MARK SPENCER"
In this code, I want it to print out like this;
12343212
MARK
SPENCER
But, it prints like this;
12343212 MARK
SPENCER
Can you help me fix it please?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
char * pch;


  pch = strtok (array[14]," ");

  while (pch != NULL)

  {

    printf ("%s\n",pch);

    pch = strtok (NULL, " ");

  }
Your code seems fine except that line 4 is a bit suspicious. Why are you passing array[14] as the argument?
Can you show the type of array?


[edit]: typo
Last edited on
Hi unoriginal;
I read a file like this;
23454323 ABCD EFGH
34565434 KLMN OPRS
...
12342312 MARK SPENCER

After I read it, i created an array of strings like this;
string array[100], so that each element will be a line;
a[1] = 23454323 ABCD EFGH
a[2] = 34565434 KLMN OPRS
..
a[14] = 12342312 MARK SPENCER
This part works because when I say print a[i] element, it just prints that line. I passed a[14] because I want to split that line. As you said, it looks fine without a problem. But now I see that the first space character is actually made with tab key, which is after 12343212 before MARK. How can I include the tab keys also as the tokens?
Last edited on
I would be tempted to use a std::istringstream:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string>
#include <sstream>
#include <iostream>

int main()
{
	std::string str = "23454323 ABCD EFGH";

	std::istringstream iss(str);

	std::string word;
	while(iss >> word)
	{
		std::cout << word << '\n';
	}
}
23454323
ABCD
EFGH


std::istringstream
http://cplusplus.com/reference/iostream/istringstream/

operator>>
http://cplusplus.com/reference/iostream/istream/operator>>/
Last edited on
Thanks for the code and links!
Topic archived. No new replies allowed.