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