0

I've been writing this code, but I don't really know what's wrong. I'm a bit of a beginner, but I'm still able to see that this is a scoping issue. Regardless, it seems to work if there is a cout statement. Why? I've tried using j as a static integer but it didn't work. Perhaps simply because I did not understand it well enough.

int id, i(0), j;
cout << "Please type the ISBN # and ID # of the copy you wish to delete." << endl;
cin >> thecopy >> id;
string fname = "../data/" + thecopy + ".txt";
ifstream fin(fname.c_str());

while (fin.good()){
    fin >> c[i];
    if(c[i].ID == id){
        j = i;
    }
    cout << j; //this statement makes it so j keeps its value
    i++;
}
    //cout << j ; this always gives 0
if(c[j].reader != "None"){
    cout << "The copy is currently lent out, so it cannot be deleted.\n";}
else {
....}

Thanks!

  • 2
    Please read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) Your reading loop is just the same really. – Some programmer dude Dec 04 '17 at 08:43
  • 2
    Also, if the condition inside the loop is never true, then `j` will never be initialized, and you use its *indeterminate* value after the loop which leads to *undefined behavior*. – Some programmer dude Dec 04 '17 at 08:45
  • _Does not work_ - meaning? –  Dec 04 '17 at 09:42
  • What is `c` and `i` in `fin >> c[i]`? Perhaps this is writing out-of-bounds? – Bo Persson Dec 04 '17 at 10:28
  • 1
    We are not going to be able to replicate and help you solve your problem without a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). Also please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), and [learn how to debug your programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Some programmer dude Dec 04 '17 at 11:16

0 Answers0