I'm trying to code the following program to read a single word per line from a text document, then print the same words to another text document, but for some reason I am encountering a rather large error after adding in:
for(int i = 0; i < num_lines; i++)
{
getline (myfile_in, line);
stringstream(line) >> arr[i];
}
Im not sure why this is causing an error because I copied this loop from a program that I wrote previously. The error goes away once i remove the stringstream line, but as far as I'm aware, I need it in order to copy the contents over to the array. Any help would be greatly appreciated :)
#include <fstream>
#include <string>
#include <sstream>
#include <assert.h>
using namespace std;
int main(void)
{
ifstream myfile_in;
myfile_in.open ("words_in.txt");
ofstream myfile_out;
myfile_out.open ("words_out.txt");
string line;
int num_lines = 0;
string *arr;
assert (!myfile_in.fail());
myfile_in >> line;
while (!myfile_in.eof())
{
getline (myfile_in, line);
num_lines++;
}
arr = new string[num_lines];
for(int i = 0; i < num_lines; i++)
{
getline (myfile_in, line);
stringstream(line) >> arr[i];
}
for(int i = 0; i < num_lines; i++)
{
myfile_out << arr[i] << endl;
}
myfile_in.close();
myfile_out.close();
return 0;
}
while (!myfile_in.eof())I believe you will read past the end of the file this wayarr[i] = lineorarr[i] = string(line)?stringstream(line) >> arr[i]accomplish a similar thing?