.txt to c++

I am trying to convert a .txt file to an array in c++. The problem is the text file contains:

a letter a number a letter a letter a letter a number
a letter a number a letter a letter a letter a number

I want to create a 2d array so that it will look like this

(a letter) (a number) (a letter a letter a letter) (a number)
(a letter) (a number) (a letter a letter a letter) (a number)

How can I let c++ ignore the spaces between the mid three letters and consider the spaces between the letter and the number only and what will be the type of array?

Thanks
Type of the array would be std::string, if you'd like.

You can use this is the pattern is sure to be how you've mentioned.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
#include <fstream>
#include <vector>

int main() {

	std::vector< std::vector< std::string> > arr;
	std::ifstream file("lol.txt");
	std::string word, temp;

	for (int i = 0; i<2; i++) {
		arr.resize(i + 1);

		arr[i].push_back(word);
		file >> word;
		arr[i].push_back(word);

		for (int i = 1; i <= 3; i++) {
			file >> word;
			temp += word;
			temp += ' ';
		}
		arr[i].push_back(temp);
		temp.clear();

		file >> word;
		arr[i].push_back(word);	
	}

	for (auto& i : arr) {
		for (auto& j : i) {
			std::cout << j;
		}
		std::cout << '\n';
	}

	std::cin.ignore(INT_MAX, '\n');
	std::cin.get();
}
Last edited on
Yet another retarded answer by Grimes! Anyway...

Your description is not entirely clear.
Do you mean:
a 1 b c d 2
e 3 f g h 4

How about an array of structs.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

struct Record {
    char a;
    int  x;
    char b[4];
    int  y;
};

int main() {
    std::vector<Record> records;
    std::ifstream in("filename");
    std::string line;
    while (std::getline(in, line)) {
        std::istringstream ss(line);
        Record rec;
        if (!(ss >> rec.a
                 >> rec.x
                 >> rec.b[0]
                 >> rec.b[1]
                 >> rec.b[2]
                 >> rec.y))
            continue;
        rec.b[3] = '\0';
        records.push_back(rec);
    }
    for (const Record& r: records)
        std::cout << r.a << ", " << r.x << ", " << r.b << ", " << r.y << '\n';
}

Last edited on
another option is that letters ARE numbers. if the numbers in the file are integers a simple array of integers will work, can a quick cast on the letter columns back to char if needed (say, to print them) would work fine.

int derp[] = {1234, 'x', 5678, 'j'};
cout << (char)(derp[1]) << endl; // writes the x letter out.
cout << derp[0]; //writes the 1234 number out.

and so on.

the standard >> operator on files will ignore whitespace.
Last edited on
Problem solved, thank you, guys
Topic archived. No new replies allowed.