文本文件读取和动态数组中的 EMTY 空间传递问题

issue with text file reading and emty space passing in dynamic array

本文关键字:空间 EMTY 问题 读取 文件 动态 数组 文本      更新时间:2023-10-16

我需要 c++ 中的帮助,将文本从文件读取到动态数组中。

文件

Regbis 
Vardenis Paverdenis
Jonas Puikuolis
Gediminas Jonaitis
Futbolas 
Tadas Pilkius
Justas Julis
Tenisas 
Ricerdas Berankis

我尝试了这样和另一种方式whilegetline s.empty,但它对我不起作用。

using namespace std;
struct struktura{
char team;
char lastname;
char firstname;
} sarasas[999];
int main()
{
char x [200];
int kiek;
ifstream duomenys;
duomenys.open("duom.txt");
int row, col;
while (!duomenys.eof())
{
    cout << "How many teams" << endl;
        cin >> row;
    int **a = new int *[row];
    for (int i = 0; i < row; i++)
    {
        cin >> col;
        a[i] = new int[col];
    }
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            duomenys >> a[i][j];
            cout << a[i][j] << "   ";
        }
        cout << endl;
    }
    }
    system("Pause");
   return 0;
 }

好的,这有很多问题。我首先对字符串使用 std::string,对动态数组使用 std::vector

然后,我将努力定义数据结构至少合理一半。我认为总体思路是这样的:

struct team { 
    std::string name;
    std::vector<std::string> players;
};

然后我会为团队定义一个operator>>,如下所示:

std::istream &operator>>(std::istream &is, team &t) {
    std::vector<std::string> players;
    std::string temp;
    // If we can't read a team name, return signaling failure:
    if (!std::getline(is, temp))
        return is;
    // save the team name
    t.name = temp;
    // and read the player's names:
    while (std::getline(is, temp)) {
        if (temp.empty())  // empty line--end of this team's players
            break;      
        players.push_back(temp);
    }
    t.players = players; // Write the player's names into the destination
    is.clear(); // and signal success, since we read a team's data
    return is;
}

从那里,我们可以读取文件中的所有团队:

std::ifstream in("teams.txt");
std::vector<team> teams { std::istream_iterator<team>{in},
                          std::istream_iterator<team>{} };