1

why doesn't this work? I am not getting an error, my program just crashes.

    ifstream inStream;
    inStream.open("Sample Credit Card numbers.txt");
    string next[100];
    for (int i = 0;!inStream.eof();i++)
    {          
        next[i] = inStream.get();//fill in the array with numbers from file
    }

i think that the !inStream.eof() part of the for loop may be the problem but i am not really sure.

greut
  • 4,169
  • 1
  • 24
  • 46

3 Answers3

0

try this:

for (int i = 0; ! inStream.eof() && i < 100; i++)

If you can debug you program then you can step in the for loop and find out what's wrong if it still crashes.

juergen d
  • 186,950
  • 30
  • 261
  • 325
0

Looping until eof() is almost certainly not what you want to do. See Why is iostream::eof inside a loop condition considered wrong? .

istream::get() extracts a character from the stream and returns its value (cast to an int) but you're putting this into an array of std::string. This seems odd.

You've also hard-coded an array of 100 elements, but have no check to ensure you don't over-run the buffer.

Instead you should prefer something like this:

std::ifstream inStream("Sample Credit Card numbers.txt");
if (inStream)
{
    std::string number;
    std::vector<std::string> next;
    while (std::getline(inStream, number))
    {
        next.push_back(number);
    }
}
else
{
    // Failed to open file. Report error.
}
Community
  • 1
  • 1
Johnsyweb
  • 121,480
  • 23
  • 172
  • 229
  • Doesn't this require the numbers to be formatted with newlines? Slightly different behavior than before, although possibly desirable. – Benj Jan 19 '12 at 17:29
  • It does. It was just a sample as to how to loop over the lines in a file. The file format is not clear (although the extension is ".txt", which implies text rather than binary). – Johnsyweb Jan 19 '12 at 17:37
0

Your program actually works just fine for me with a smallish set of numbers in the file. However 2 things may be causing you a problem:

  1. You don't check if the file was opened successfully and this would crash if it didn't.
  2. You don't check if you have enough strings in your array, what if you have more numbers in your file than 100 ? This would also cause a crash.
Benj
  • 29,382
  • 17
  • 72
  • 119