1

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;
    }
}
user1030
  • 23
  • 2
  • I read somewhere sometime today that you have to specify the full path of the file if you are on a Mac. Can't verify sorry, but worth a try :) – Rakete1111 Jul 21 '16 at 05:08
  • try "./mytext.txt" –  Jul 21 '16 at 05:09
  • Your code works just fine for me. Is the *.txt file really in the same directory as the compiled executable? Because it's definitely not a problem with the code, didn't have to specify the full path either. – Fang Jul 21 '16 at 05:15

1 Answers1

5

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); 
    }
    
Community
  • 1
  • 1
R Sahu
  • 196,807
  • 13
  • 136
  • 247
  • Thank you! I copied your suggests in the code and now it returns "unable to open file". Do you have any idea, why? – user1030 Jul 22 '16 at 15:07
  • @user1030, it's most likely that run directory is different from the location of the file. Try the absolute path of the file, just to be sure that there aren't any permission issues. – R Sahu Jul 22 '16 at 15:12
  • @RSahu Nope, sorry, it works though, thank you again!! Language differences, my os is not in English, neither the main directory... – user1030 Jul 22 '16 at 15:55