user1030
user1030

Reputation: 23

Why does this code turn back blank console while trying to put a .txt into a vector and cout it?

I am trying to open a .txt using a void function named ‘scan’ and a vector called ‘lines' but the console keeps returning blank. The same code ran perfectly on Windows but not on Mac (both with Codeblocks). What went possibly wrong? The .txt file is in the same folder as the whole project.

#include <iostream>
#include <fstream> 
#include <vector>
using namespace std;

void scan(vector<string> &lines)
{
    ifstream fin("mytext.txt"); 
    string str;

    while(!fin.eof())
    {
        getline(fin, str); 
        lines.push_back(str); 
    }
}



int main()
{
    vector <string> lines;
    scan(lines); 

    for(int i=0; i<lines.size(); i++)
    {
        cout<<lines[i]<<endl;
    }
}

Upvotes: 1

Views: 74

Answers (1)

R Sahu
R Sahu

Reputation: 206607

Things you can change to make it easier to troubleshoot where the problem is:

  1. Always check whether open was successful.

    ifstream fin("mytext.txt");
    if ( !fin.is_open() )
    {
       std::cerr << "Unable to open file.\n";
       return;
    }
    
  2. Use of while(!fin.eof()) is not right. See Why is iostream::eof inside a loop condition considered wrong?. Change the loop to:

    while(getline(fin, str))
    {
        lines.push_back(str); 
    }
    

Upvotes: 5

Related Questions