C++ 从文本文件中获取数组字符串
c++ get array string from text file
我的文本文件就像
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(( 在格式化提取后跳过输入?
相关文章:
- 如何在 nlohmann 的 json 库中获取数组长度?
- 从用户那里获取数组大小的值
- 如何在VS2019中获取数组的任意对齐?
- 我如何获取数组的大小,以便我可以从函数声明所述数组
- 根据字符获取数组的索引
- 尝试递归获取数组元素的总和
- 用于获取数组长度的指针数学
- Socket.io客户端C++,从Socket.on获取数组
- C++ nlohmann JSON 获取数组名称
- 练习循环和使用循环 1 次以及如何获取数组的最大值
- 如何在函数参数中通过引用获取数组
- 如何获取数组中字符串元素的字符数?[C++]
- 如何声明一个未知大小的数组,然后输入直到我想要,然后获取数组的大小
- 无法获取数组内数组的总和
- 尝试获取数组中的最小元素时崩溃
- 获取数组类型的无效错误
- 如何从用户获取数组输入
- 使用位集获取数组项的条件总和,而无需使用循环
- 如何以模式获取数组中的数据?
- 如何获取数组中每个数字的平方根 (C++)