Hey Everyone! I'm having trouble with a C++ program I'm trying to write. I need to input a text file into a 2D array and sort it into 13 rows, 5 columns using strtok. I need to use strtok because some of the words are separated by ws, others by a comma.

For example,
123 Mike November,12 1990

I'm not sure how to use the strtok when I'm creating the array from the file. Before I thought of strtok, I was making 4 column 2D-arrays by just doing myFile>>_array[j]; (which is what my code shows below).

If anyone could help me out with this I would really appreciate it!! :)

#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
	const int ROWS = 13;	
	const int COLS = 4;	
        string _array[ROWS][COLS];	
        ifstream myFile("data.txt");	
	ofstream myFileOut("data2.txt");

	for (int i = 0; i < 12; i++){	
		for(int j = 0; j < 4; j++){
			myFile >> _array[i][j];

	for (int i = 0; i < 12; i++){
		cout << "\n";
		for (int j = 0; j < 4; j++){	
			cout << _array[i][j] << " "; 
			myFileOut << _array[i][j] <<endl;	

    return 0;			
8 Years
Discussion Span
Last Post by rugs267

don't use strtok() on std::string objects because strtok() will put 0s in the string which will invalidate the std::string object.

The c++ way to achieve this is

int main()
    string str = "123 Mike November,12 1990";
    size_t pos = str.find_first_of(" ,");
    while(pos != string::npos)
        cout << str.substr(0, pos) << "\n";
        str = str.substr(pos+1);
        pos = str.find_first_of(" ,");
    cout << str << "\n"; // display the last word in the strihng


OK that makes a lot of sense. But I'm still not sure how I would get these strings into a 2D array. What if I have 13 lines of similar entries from a text file? I just don't know how to incorporate both.


use getline() to retrieve the entire line as one string, then run it through the code I posted. instead of writing each individual string with cout put it in the array like you previously posted.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.