Reading data from a file separated by spaces

Hello! I am a newbie learning C++
I'm currently writing a program that will read data from a file "scores.txt" and store those scores in an array, maybe a vector, I'm not sure which is proper form. The number of lines in the file is variable and each line would look something like this:
score1<space>score2

This is the code I currently have but it only reads one value per line and not separated by spaces.

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
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main() {

	vector<int> numbers;

	//Create an input file stream
	ifstream in("scores.txt",ios::in);

	/*
            As long as we haven't reached the end of the file, keep reading entries.
	*/

	int number;  //Variable to hold each number as it is read
	
        while (in >> number) {
		//Add the number to the end of the array
		numbers.push_back(number);
	}

	//Close the file stream
	in.close();

	//Display the numbers
	cout << "Numbers:\n";
	for (int i=0; i<numbers.size(); i++) {
		cout << numbers[i] << '\n';
	}

	cin.get(); //Keep program open until "enter" is pressed
	return 0
Last edited on
One way is to use two vectors, one to hold score1 and another to hold score2.

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
#include <iostream>
#include <fstream>
#include <vector>

int main() {

    std::vector<int> first_score ;
    std::vector<int> second_score ;

    //Create an input file stream
    std::ifstream in( "scores.txt" );

    // As long as we haven't reached the end of the file, keep reading entries.
    int s1, s2 ;
    while( in >> s1 >> s2 ) { // for each pair of scores read from the file

        // Add the scores to the end of the vectors
        first_score.push_back(s1);
        second_score.push_back(s2);
    }

    //Display the scores
    std::cout << "scores:\n";
    for( std::size_t i=0; i < first_score.size(); ++i ) {

        // print the two scores with a space in between them
        std::cout << first_score[i] << ' ' << second_score[i] << '\n';
    }
}


Another is to use a struct to hold the two scores; that would be better if you are familiar with structures.
Hello ToeMater,

Another option would be a vector of "std::pair", i.e., std::vector<std::pair<int, int>> numbers;. "std::pair" will need the header file "utility".

I do like JLBorges's idea of the vector of structs.

Hope that helps,

Andy
Thank you very much it worked perfectly.
:)
Topic archived. No new replies allowed.