using getline to get multiple lines from a file and input them in different arrays

StackOverflow https://stackoverflow.com/questions/21888378

  •  13-10-2022
  •  | 
  •  

Pregunta

I'm trying to do a simple getline from a filestream and then store the different input into different arrays.

The input file is something like this.

Course Of Sales Time,Price ($),Volume,Value ($),Condition 10/10/2013 04:57:27 PM,5.81,5000,29050.00,LT XT 10/10/2013 04:48:05 PM,5.81,62728,364449.68,SX XT 10/10/2013 04:10:33 PM,.00,0,.00,

Note that the first two lines are redundant and should be ignored. All data should be stored in their respective arrays like time[i], price[i].

string datefield;
int count = 0;
string date[5000];
float pricefield;
float price [5000];
int volume[5000];
float value[5000];
string condition[5000];
int i = 0;

while (!infile.eof()) {
    count++;
    getline(infile,datefield);
    while (count >= 2) {
        getline(infile,date[i], ',');
        infile  >> price[i] >> volume[i];
        i++;
        break;
    }
}

The problem here is, no input is going into volume[i].

¿Fue útil?

Solución

  1. Don't put eof() in the while condition. It's wrong! Check out: Why is iostream::eof inside a loop condition considered wrong?. To work out, you can change

    while (!infile.eof()) {
        count++;
        getline(infile,datefield);
        ... 
    

    to

    while (getline(infile,datefield)) {
        count++;
        ... 
    
  2. You should be very careful in the data reading step. For ",.00,0,.00,", as there is no spaces within it, thus >> price[i] >> volume[i] will try to read all these content to price[i]. No content will be read into volume[i]. To work out, you can first read this part to a string and then read the data from it by splitting. Or replace all ',' to spaces and then put it into a std::istringstream, then you can use >> price[i] >> volume[i] correctly.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top