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

Recommended Answers

All 4 Replies

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.

Thank you so much for all your help!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.