чтение в строках и парных разрядах - PullRequest
1 голос
/ 26 апреля 2011

У меня проблема с чтением в строку из файла, а затем дважды из файла после этого.Мой профессор посоветовал мне ставить специальную строку getline после каждой строки ввода, но она не сработала, и я понял, что это проблема программы.Есть ли более простой способ взять двойные числа?

пример входного файла:

John Smith
019283729102380
300.00
2000.00
Andrew Lopez
293481012100121
400.00
1500.00

код гласит:

while(! infile.eof())
{
getline(infile,accname[count],'\n');
getline(infile, refuse, '\n');  
getline(infile,accnum[count],'\n');
getline(infile, refuse, '\n');  
infile>>currbal[count];  
getline(infile, refuse, '\n');  
infile>>credlim[count];  
getline(infile, refuse, '\n');  
count++;
}

Ответы [ 3 ]

2 голосов
/ 26 апреля 2011

РЕДАКТИРОВАТЬ: Обновлено в ответ на разъяснения ОП.

На основании предоставленного вами образца это должно работать:

while(1) {
    std::string s1;
    if(!std::getline(infile, s1))
        break;
    std::string s2;
    if(!std::getline(infile, s2))
        break;
    double d1, d2;
    if(!(infile >> d1 >> d2))
        break;
    accname[count] = s1;
    accnum[count] = s2;
    currball[count] = d1;
    credlim[count] = d2;
    count++;
}

Этот код будет работать для ввода, как:

Adam Sandler
0112233
5 100
Ben Stein
989898
100000000
1

Но он не будет работать для ввода, как:

Adam Sandler

0112233

5 100

Ben Stein

989898

100000000

1
0 голосов
/ 03 мая 2013
string str;

while(!infile.eof())
{
    getline(infile, accname[count]);//  you do not need '\n' it will always read to 
                     // end of the line

    getline(infile, accnum[count]);

    getline(infile, str);
    currbal[count] = atof(str.c_str());

    getline(infile, str);
    credlim[count] = atof(str.c_str());

    count++;
}

\* 
for the file 
John Smith
019283729102380
300.00
2000.00
Andrew Lopez
293481012100121
400.00
1500.00
*\
0 голосов
/ 26 апреля 2011

Я думаю, что у ответа Роба Адамса есть небольшая ошибка при разборе нескольких записей. После первого извлечения d2 пример входного потока будет содержать \nBen Stein\n989898\n100000000\n1, поэтому следующий вызов std::getline() извлечет пустую строку вместо Ben Stein. Поэтому представляется необходимым использовать пустую строку в конце каждой итерации цикла while.

Я думаю, что следующий пример кода дает исправление:

#include <iostream>
#include <sstream>

int main(int argc, char** argv) {
  using std::stringstream;
  stringstream infile(stringstream::in | stringstream::out);

  infile << "John Smith\n";
  infile << "019283729102380\n";
  infile << "300.00\n";
  infile << "2000\n";
  infile << "Andrew Lopez\n";
  infile << "293481012100121\n";
  infile << "400.00\n";
  infile << "1500.00\n";

  std::string account_name;
  std::string account_number;
  double current_balance;
  double credit_limit;

  int count = 0;

  while (std::getline(infile, account_name) &&
         std::getline(infile, account_number) >> current_balance >>
         credit_limit) {

    std::cout << account_name << std::endl;
    std::cout << account_number << std::endl;
    std::cout << current_balance << std::endl;
    std::cout << credit_limit << std::endl;

    /*
    accname[count] = account_name;
    accnum[count] = account_number;
    currball[count] = current_balance;
    credlim[count] = credit_limit;
    */

    count++;

    // Consume the leading newline character, which seprates the credit limit
    // from the next account name, when infile contains multiple records.
    //
    // For example, after consuming the record for John Smith, the stream will
    // contain: "\nAndrew Lopez\n293481012100121\n400.00\n1500.00\n". If you
    // don't consume the leading newline character, calling std::getline() to
    // parse the next account name will extract an empty string.
    std::string blank;
    std::getline(infile, blank);
  }

  return 0;
}
...