Reading lines from a file into an array
Sep 1, 2014 at 10:50pm UTC
I'm working on a few warm-up exercises out a book. The first part of the exercise is to read the lines from a file placing each line into an array. I thought my code looked correct however nothing but garbage prints out. Here's my code. I don't know what I'm doing wrong. I would really appreciate the help so I can move on the 2nd part of exercise.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const size_t ARRAY_SIZE = 50;
///read the lines from a file placing each line in an array element
void readLines(ifstream& msgFile, string line[], int arraySize);
void readLines(ifstream& msgFile, string line[], int arraySize)
{
size_t i = 0;
while (msgFile && i < arraySize)
getline(msgFile, line[i]);
cout << line << endl;
i++;
}
int main(int argc, char ** argv)
{
if (argc != 4)
{
cerr << "Usage: " << argv[0] << " msgFILE replaceFile outputFile" << endl;
return -1;
}
ifstream msgTxt(argv[1]);
ifstream replaceTxt (argv[2]);
ofstream outputTxt (argv[3]);
string line[ARRAY_SIZE]; //creates an array of strings
readLines(msgTxt, line, ARRAY_SIZE);
return 0;
}
Sep 1, 2014 at 11:29pm UTC
Take a closer look at line 18.
Sep 1, 2014 at 11:39pm UTC
1 2 3 4 5 6 7 8 9 10
void readLines(ifstream& msgFile, string line[], int arraySize)
{
size_t i = 0;
while (msgFile && i < arraySize)
{
getline(msgFile, line[i]);
cout << line << endl;
++i;
}
}
o.o ?
Topic archived. No new replies allowed.