Reputation: 23
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
Reputation: 206607
Things you can change to make it easier to troubleshoot where the problem is:
Always check whether open
was successful.
ifstream fin("mytext.txt");
if ( !fin.is_open() )
{
std::cerr << "Unable to open file.\n";
return;
}
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