Home > Back-end >  How to use first number in text file as header, then read in the remaining numbers?
How to use first number in text file as header, then read in the remaining numbers?

Time:12-09

I have a text file that looks like

6
0 0 0 
1 1 0
2 1 1
3 3 1
4 3 5
5 4 6

The first number tells the program how many rows of numbers come after it. How can I read in the first number for n, then read in the rest? When I remove the "fin>>n" and the "6" from the text file, the code works correctly. My code for this section looks like

if ( ! fin.is_open() ) {
cout<< "error opening file" << endl;
return 1;
}
else{
  fin>>n;
 for (int i=0; i<n; i  ){
 fin>> time[i] >> x[i] >> y[i];}

CodePudding user response:

You can use std::vector and std::getline for achieving this as shown below:


#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
int main()
{
    std::ifstream inputFile("input.txt");
    std::vector<int> time,x,y; 
    std::string line,tempRows;
    int rows;
    if(inputFile)
    {
        //get first value 
        std::getline(inputFile, tempRows);
        std::istringstream ss(tempRows);
        ss >> rows;
        
        //resize the vectors
        time.resize(rows);
        x.resize(rows);
        y.resize(rows);
        int i = 0;
       while(std::getline(inputFile, line) && (i < rows))//read line by line
            {
                std::istringstream ss2(line);
                ss2 >> time[i];
                ss2 >> x[i];
                ss2 >> y[i];
                  i;
            }
    }
    else 
    {
        std::cout<<"File cannot be opened";
    }
    //lets print out the elements of the vectors to confirm that we have read the values correctly
    for(int i = 0; i < rows;   i)
    {
        std::cout<< time[i] <<" "<<x[i] <<" "<<y[i]<<std::endl;
    }

    return 0;
}

The output of the program can be seen here.

CodePudding user response:

Try using scanf().

int a;
scanf("%d", &a);
for (int i = 0; i < a; i  ) {
    scanf("%d %d %d", &myVar1, &myVar2, &myVar3);
}
  •  Tags:  
  • c
  • Related