Reputation:
I need to read a file and turn it into a string array but when it reads the file it doesn't put anything in the array. Here's my current code:
string code[200];
string name;
int lines;
string filename;
int readfile(){
ifstream inFile;
int counter = 0;
cout << "Which file would you like to open?\n";
cin >> filename;
countlines();//counts total lines of file
inFile.open(filename);
if(inFile.fail())
{
cout << "File did not open correctly, please check it\n";
system("pause");
exit(0);
//return 1;
}
inFile >> name;
for (int i=0;i < lines; i++)
{
inFile >> code[i];
if (!inFile)
cout << "Error" << endl;
break;
}
inFile.close();
cout << "Now opened: " << name << endl;
return 0;
}
Upvotes: 1
Views: 1894
Reputation: 1988
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
vector<string> lines;
bool readFile(string filename){
ifstream file;
string line;
file.open(filename.c_str());
if(!file.is_open()){
return false;
}
while (getline(file, line)) {
lines.push_back(line);
}
return true;
}
int main(){
readFile("test.txt");
for(int i = 0; i < lines.size(); ++i){
cout << lines[i] << endl;
}
return 0;
}
Upvotes: 1
Reputation: 10722
You need to change
inFile.open(filename);
to:
inFile.open(filename.c_str());
Upvotes: 0
Reputation: 4325
This is a much simpler implementation of line reading which doesn't crash if the file has more than 200 lines:
vector<string> code;
string s;
while (getline(inFile, s)) {
code.push_back(s);
}
Upvotes: 0