I'm writing a program which will double space any given input text file. My code below works but it only works once. If I try to run it the second time for the same file, it would give me an access violation error. I've tried to track the indexes when I copy the line to the string array and don't see any index goes out of bound. Could anyone please tell me where the problem is ?
I've been able to fix the problem by replacing the while loop by the for loop. However, I still don't understand why I had the problem with the while loop like above. Could anyone tell me what the problem was? Thanks in advance.
Also the code below is the part which I changed to fix the problem.
1 2 3 4 5 6 7 8 9 10 11 12 13
string* line = new string [count];
inFile.open("dog or cat.txt");
if (inFile.is_open())
{
for (int i = 0; i < count; i++)
{
getline(inFile,line[i]);
}
}
else
cout <<"Something's wrong" << endl;
Didn't actually run your code, but it looks like the problem is on line 26, it will still attempt to access an out-of-bounds index [i] before getline actually fails.
e.g. file
apple
banana
carrot
Lines 7-13: count --> 3 (indices 0, 1, 2)
Lines 25-29:
i = 0
access line[0] --> OK
getline --> good
i = 1
access line[1] --> OK
getline --> good
i = 2
access line[2] --> OK
getline --> good
i = 3
access line[3] --> ERROR out of bounds, undefined behavior
getline --> {doesn't matter what happens, you already have undefined behavior}
In addition to what Ganado has said I made a change to line 19. I changes "count" to "count + 1" and the program worked fine with the while loop.
The other thing I had to do to get the program to compile is change "_tmain" to "main". And I removed everything in the ()s because "_TCHAR" was also a problem. Also "argc" and "argv" are not used in the program, so there is no need for them to be there. After making these changes the program compiled.
I do not use dynamic arrays that often, but I am thinking that the size of the array that is created is something + 1. Or it could have been the blank lines in the text file that I used creating the problem. Not sure yet.