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

c++ get array string from text file

本文关键字:获取 数组 字符串 文件 文本 C++      更新时间:2023-10-16

我的文本文件就像

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 filen";
        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;
        }
    }
}

>> 一起使用 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 << "nn";
  }
  return 0;
}

另一个建议是对数组使用 vectors record,并使用 strings 而不是 char 数组。

引用:

为什么 std::getline(( 在格式化提取后跳过输入?