gpt4 book ai didi

c++ - 从文件中读取字符串并将其不同部分保存在 C++ 中的不同变量中

转载 作者:行者123 更新时间:2023-11-28 07:46:14 25 4
gpt4 key购买 nike

所以我有这个包含一些字符串和数字的文件,它来自西类牙足球联赛:

Malaga 1 Levante 1
Malaga 1 Osasuna 1
Osasuna 1 Deportivo 1
Osasuna 1 Madrid 2
Osasuna 1 Levante 1
Osasuna 1 Malaga 1
#

好的,我要做的是阅读这篇文章,然后将不同的球队(马拉加、莱万特、奥萨苏纳、拉科鲁尼亚和马德里)保存在 5 个不同的变量中,我还必须将他们的进球保存在每个球队的一个变量中以及他们在每个团队的另一个目标中获得的目标。这是我的代码:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
const char FI='#';
const int MAX_EQUIPS=20;


struct Equip {
string nomEquip;
int golsf;
int golsc;
int punts;
};

typedef Equip TaulaEquip[MAX_EQUIPS];

struct EquipLliga {
TaulaEquip t;
int n;
};
int cercaEquip(EquipLliga l, string equip) {
// Pre: --
// Post: si equip no hi es a d.t, retorna -1
// altrament retorna posicio de l'equip de nom equip a d.t
int ret=l.n-1;
bool trobat= false;
while (ret>=0 and not trobat) {
if (l.t[ret].nomEquip.compare(equip)==0) trobat= true;
else ret--;
}
return ret;
}
void llegir(ifstream & f) {

string string1;
f.open("Lliga.txt");
char output;
if (f.is_open()) {
while (!f.eof()) {
getline(f,string1);
cout << string1 << endl;
}
}
f.close();
}
void actualitzacioGols(ifstream & f, EquipLliga & e) {
// Pre: f obert
// Post: ha llegit totes les dades de f, incorporat altes i traspasos a al, i els
// ingresos i despeses dels equips per altes, baixes i traspasos a d
char tipus;

string equipA, equipB;
int golsf=0, golsc=0, cerca;
e.n=0;
f >> tipus;

while (tipus!=FI) { // per cada equip
cerca=cercaEquip(e,equipA);
if (cerca=-1)
{
e[n].e.nomEquip=equipA;
e[n].e.golsf=l[n].e.golsf+golsA;
e[n].e.golsf=l[n].e.golsf+golsB;
}
else
{
e[cerca].e.golsf=l[cerca].e.golsf+golsA;
e[cerca].e.golsc=l[cerca].e.golsc+golsB;
}
lliga.n++;
cerca=cercaEquip(e,equipB);
if (cerca=-1)
{
e[n].e.nomEquip=equipB;
e[n].e.golsf=l[n].e.golsf+golsA;
e[n].e.golsf=l[n].e.golsf+golsB;
}
else
{
e[cerca].e.golsf=l[cerca].e.golsf+golsA;
e[cerca].e.golsc=l[cerca].e.golsc+golsB;
}

}
int main() {


}

我在使用函数“void actualitzacioGols(ifstream & f, EquipLliga & e)”时遇到问题。我不知道如何对其进行编码,以便它读取到第一个空格,然后将其保存到第一个团队变量“equipA”,然后将第一个数字保存到第一个目标变量“golsf”,与另外两个。

有什么想法或有用的技巧来解决这个问题吗?我是 C++ 的新手。

最佳答案

我建议你看看这篇解释 how to split a string using a delim 的帖子

在您的情况下,您可能希望使用空格来拆分字符串。由于您有固定的格式,如果您确定您的文件将始终具有相同的格式,那么您可以通过将 vector 的元素作为数组访问并使用硬编码索引来检索您想要的信息(团队和目标)。

关于c++ - 从文件中读取字符串并将其不同部分保存在 C++ 中的不同变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14836190/

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