1

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;
}
2
  • "Not working" is a very vague description. Commented Dec 9, 2012 at 2:26
  • What's the filename you're inputting? Commented Dec 9, 2012 at 2:32

3 Answers 3

1
#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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

How can I use lines in a for loop? for(int i = 0; i < lines; i++){} isn't working
for(int i = 0; i < lines.size(); ++i){ cout << lines[i] << endl;} and include <iostream>, i update the code.
Thank you! This works great, this has been bothering me all day!
0

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);
}

Comments

0

You need to change

inFile.open(filename);

to:

inFile.open(filename.c_str());

2 Comments

Probably not. In C++11, ifstream and ofstream allow you to pass in std::string for filenames. Modern implementations support this feature. Considering he didn't mention a compiler error, it's a safe bet that his compiler supports it too.
@BenjaminLindley True. He didn't mention that. I only offered that since my g++ compiler wouldn't compile the code with std::string as the parameter value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.