gpt4 book ai didi

c++ - 如何将文本文件读入结构数组? C++

转载 作者:太空狗 更新时间:2023-10-29 21:09:50 25 4
gpt4 key购买 nike

我正在尝试将一些足球运动员数据输入到足球运动员数组(结构)中

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct sPlayer{
char lname[20];
char fname[20];
int birthmonth;
int birthday;
int birthyear;
};

int main() {

sPlayer players[10] = {};
string input;
string foo;

ifstream inputFile;
inputFile.open("players.txt");

//check for error
if (inputFile.fail()){
cerr << "error opening file" << endl;
exit(1);
}

int count = 0;
while (!inputFile.eof()){

getline(inputFile, input, ' ');
players[count].lname = input;
count++;

}

inputFile.close();

cout << input;
cout << "\n2–display original data, 3–sort data , 4–display sorted data 5–search by lastname 6–exit the program\n";
}

players.txt 文件:

Roberto Baggio 01 12 1992
David Beckham 05 12 1988
Pablo Aimar 05 13 1987
Michael Ballack 11 13 1999
Gabriel Batistuta 05 05 1979
Franz Beckenbauer 18 01 1976
Dennis Bergcamp 03 14 1989
Omar Bravo 03 03 1999
Jared Borgetti 09 23 1977
Fabio Cannavaro 02 25 1991

我收到一个错误,因为我无法将 players[count].lname 分配给输入,但我不知道如何匹配我的数据类型。我正在读取 fname 和 lname 的 2 个字符数组,生日/月份/年份的 3 个整数。

最佳答案

您可以做几件事,但哪一个是正确的可能取决于您尚未告诉我们的项目的其他方面。

简单的做法是更改您的结构以使用 std::string 而不是 char 数组。

struct sPlayer{
string lname;
string fname;
int birthmonth;
int birthday;
int birthyear;
};

现在您的代码可以编译了。毫无疑问,这很容易做到,所以除非您有充分的理由使用 char 数组,否则我会这样做。

您可以做的另一件事是正确执行从 std::string 到 char 数组的赋值。 C++ 中的数组很差,如果你想复制它们,你必须采取特殊的步骤。在您的代码中,您可以使用 strcpy 函数

strcpy(players[count].lname, input.c_str());

这段代码有风险,因为如果您读取的字符串不适合您的 20 个字符数组,它就会失败。在复制之前,您应该检查这种可能性。

正如评论中已经指出的那样

while (!inputFile.eof()) {
getline(inputFile, input, ' ');
...
}

不正确。正确的版本是

while (getline(inputFile, input, ' ')) {
...
}

关于c++ - 如何将文本文件读入结构数组? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56986442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com