0

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;
}
5
  • 1
    while (!myfile_in.eof()) I believe you will read past the end of the file this way Commented Oct 15, 2015 at 7:53
  • Hmm, how would I fix this? Commented Oct 15, 2015 at 7:56
  • Why aren't you using arr[i] = line or arr[i] = string(line) ? Commented Oct 15, 2015 at 7:57
  • @malhotraprateek shouldn't stringstream(line) >> arr[i] accomplish a similar thing? Commented Oct 15, 2015 at 8:03
  • Dont know :P never used that but it seems a tad complicated... Commented Oct 15, 2015 at 8:06

2 Answers 2

1

Why not getline (myfile_in, arr[i]); ?

Sign up to request clarification or add additional context in comments.

8 Comments

I just tried that, it doesn't crash when compiling, but it just prints blank lines in the output file.
@CalebMoriarty That's because in while (!myfile_in.eof()) loop you had read all lines in the file. If you need to read them again, you can try reopening the file.
@CalebMoriarty And I believe using a std::vector may be a better solution in your problem.
Im sure it would be, but I haven't learned about that in class yet haha.
@CalebMoriarty lol. The solution is simple, add myfile_in.seekg(0) right after the while loop.
|
1

Probably, after while loop you've already read whole file. And then in for loop you again trying to readline from this stream. I think, you should remove readline command from for loop.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.