c ++从文本文件中获取数组字符串

时间:2014-08-18 01:39:29

标签: c++ text-files

我的文字文件就像

Jason Derulo
91 Western Road,xxxx,xxxx
1000
david beckham
91 Western Road,xxxx,xxxx
1000

我试图从文本文件中获取数据并将其保存到数组中,但是当我想将文本文件中的数据存储到数组中时,它会不停地循环。我该怎么办 ?循环中出现的问题或从文本文件中获取数据的方法?

代码:

#include <iostream>
#include <fstream>

using namespace std;

typedef struct {

    char name[30];
    char address[50];
    double balance;

} ACCOUNT;

//function prototype
void menu();
void read_data(ACCOUNT record[]);

int main() {
    ACCOUNT record[31]; //Define array 'record'  which have maximum size of 30
    read_data(record);  
}
//--------------------------------------------------------------------

void read_data(ACCOUNT record[]) {
    ifstream openfile("list.txt");              //open text file 

    if (!openfile) {
        cout << "Error opening input file\n";
        return 0;
    } else {
        int loop = -1;                  //size of array 
        cout << "--------------Data From File--------------"<<endl;
        while (!openfile.eof())  {
        if (openfile.peek() == '\n') 
            openfile.ignore(256, '\n');
        openfile.getline(record[loop].name, 30);
        openfile.getline(record[loop].address, 50);
        openfile >> record[loop].balance;
        }
        openfile.close();               //close text file

        for (int i = 0; i <= loop + 1; i++) {
            cout << "Account "  << endl;
            cout << "Name         : " << record[i].name << endl;
            cout << "Address      : " << record[i].address << endl;
            cout << "Balance      : " << record[i].balance << endl;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

ifstream::getline() 一起使用ifstream::eof()代替>>。以下是一个说明性示例,(为简单起见,我没有检查流是否正确打开)。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

#define ARR_SIZE 31

typedef struct {
    char name[30];
    char address[50];
    double balance;
} ACCOUNT;

int main() {
  ACCOUNT temp, record[ARR_SIZE];
  ifstream ifile("list.txt");
  int i=0;
  double d=0;

  while(i < ARR_SIZE) {
    ifile.getline(temp.name, 30, '\n');//use the size of the array
    ifile.getline(temp.address, 50, '\n');//same here

    //consume the newline still in the stream:    
    if((ifile >> d).get()) { temp.balance = d; }

    record[i] = temp;
    i++;
  }

  for (int i=0; i < ARR_SIZE; i++) {
    cout << record[i].name << "\n" 
         << record[i].address << "\n" 
         << record[i].balance << "\n\n";
  }
  return 0;
}

另一个建议是将vectors用于record数组,使用strings代替char数组。

参考文献:

Why does std::getline() skip input after a formatted extraction?