0

In my program I'm trying to read from some files, store the data into structs, and sort/display the data for an assignment. However, it wasn't quite working right, and after some troubleshooting I noticed that from every read file, the first and third words are skipped for some reason.

The relevant code:

void fillArray(string filename, string arr[])
{
    ifstream ifile(filename);
    int count = 0;
    while (getline(ifile, arr[count++]))
    {
        getline(ifile, arr[count]);
        count++;
    }
    ifile.close();
} 

The relevant files are structured that after every word there's a newline, so getline only gets and stores one word per iteration. Also, it may be relevant as well that the files being read from are entered as arguments via the command prompt.

1 Answers1

0
   while (ifile >> arr[count])
    {
        getline(ifile, arr[count]);
        count++;
    }

ifile >> arr[count] reads a word & without count being incremented, getline reads the rest of the line & overwrites what was read by ifile >> arr[count]

That may be the cause of some words being skipped - the words read by >> are overwritten.

user93353
  • 12,985
  • 7
  • 50
  • 106
  • So I tried replacing `ifile >> arr[count]` with `getline(ifile, arr[count++])` in the condition and it works now! Thanks a ton. – Davin Duran Nov 24 '20 at 06:09