I'm quite new to C++, so sorry if this is a dumb question!
For a project we are given a file with a couple of thousand lines of values, each line having 9 different numbers.
I want to create a for/while loop that, for each loop, stores the 8th and 9th integer of a line as a variable so that I can do some calculations with them. The loop would then move onto the next line, store the 8th and 9th numbers of that line as the same variable, so that I can do the same calculation to it, ending when I've run out of lines.
My problem is less to do with reading the file, I'm just confused how I'd tell it to take only the 8th and 9th value from each line.
In your real program, to get the first number of the first line, use numbers[0][0]. The first of the second line numbers[1][0]. The second, from de second line numbers[1][1]...
I was just thinking, the text file I'm trying to input is about 100,000 lines long so maybe a vector isn't the best way to do this, would there be another way?
> I want to create a for/while loop that, for each loop, stores the 8th and 9th integer of a line
> as a variable so that I can do some calculations with them.
> The loop would then move onto the next line, store the 8th and 9th numbers of that line
> as the same variable, so that I can do the same calculation to it, ending when I've run out of lines.
#include <fstream>
#include <string>
#include <sstream>
int main()
{
std::ifstream file( "file name here" ) ; // open the file
constint N_DISCARDED = 7 ; // we are not interested in the first seven numbers
std::string line ;
while( std::getline( file, line ) ) // for each line in the file
{
// create an input string stream to read from the line
std::istringstream stm(line) ;
// extract and throw away the first NUMBERS_DISCARDED numbers
double /* int? */ number ;
for( int i = 0 ; i < N_DISCARDED ; ++i ) stm >> number ;
// extract the 8th and 9th integers
int number8 ;
int number9 ;
if( stm >> number8 >> number9 ) // if the line did contain nine numbers
{
// do some calculations with number8 and number9
// store the result somewhere (if required)
}
}
}
> I was just thinking, the text file I'm trying to input is about 100,000 lines long
> so maybe a vector isn't the best way to do this,
On a typical implementation, 100K lines with two integers per line stored into a vector would take a maximum of about 1.6 MB. You can afford that quite easily, if storing all the numbers is actually needed.