user1730332
user1730332

Reputation: 85

I want to read from a file which has spaces c++ ifstream

My file looks like this

0 0 5
1 10 20
2 10 10
3 15 3
4 20 30
5 25 5

and I am saving this in a vector. I am not sure how to read it so that I can save each component in a different vector.

Attempt at a solution:

if (inFile.is_open()) { 
     while ( inFile) { 
          getline (inFile,line); 
          cout << line << endl; 
     } 
     inFile.close(); 
}

Upvotes: 0

Views: 170

Answers (1)

sgarizvi
sgarizvi

Reputation: 16796

I think this is what you want to do:

ifstream fin("C:/file.txt");

if(!fin)
{
    cout<<"Cannot Open File";
    exit(EXIT_FAILURE);
}

vector<vector<int>> v;

int vector_length = 3;

int count = 0;
while(!fin.eof()) //Read till the end of file
{       
    v.push_back(vector<int>()); //Add vector for new line
    int number;
    for(int i=0; i<vector_length; i++)
    {
        fin>>number;  //Read a number from the file
        v[count].push_back(number);  //Add the number to the vector
    }
    count++;
}


//Show the output to confirm that the file has been read correctly
for(int i=0; i<v.size(); i++)
{
    for(int j=0; j<v[i].size(); j++)
    {
        cout<<v[i][j]<<"\t";
    }
    cout<<endl;

}

Upvotes: 1

Related Questions