【问题标题】:Getline and parsing dataGetline 和解析数据
【发布时间】:2025-12-30 19:00:12
【问题描述】:

我的程序需要从包含不超过 50 个玩家统计数据的文本文件中读取。输入示例如下:

Chipper Jones 3B 0.303
Rafael Furcal SS 0.281
Hank Aaron RF 0.305

我的问题是我似乎无法弄清楚如何解析每一行中的数据。我需要帮助弄清楚我将如何做到这一点,以便输出如下所示:

Jones, Chipper: 3B (0.303)
Furcal, Rafael: SS (0.281)
Aaron, Hank: RF (0.305)

我的目标是创建某种循环,该循环将遍历任何可用的行,解析这些行,并将每行的内容建立到与其关联的变量。

代码:

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

using namespace std;

class player
{
private:
    string first, last, position;
    float batave;
    int a;

public:
    void read(string input[50]);
    void print_data(void);

} playerinfo;

void player::print_data(void)
{
    cout << last << ", " << first << ": " << position << " (" << batave << ")" << endl;
}

void player::read(string input[]) // TAKE INFORMATION IN THE FILE AND STORE IN THE CLASS
{
    for (int a = 0; a <= 50; a++);
    {
        // getline(input[0], first, ' ', last, );
    }

}



int main(void)
{
    ifstream infile;
    string filename;
    ofstream outfile;
    string FILE[50];

    cin >> filename;

    infile.open(filename.c_str());

    if (!infile)
    {
        cout << "We're sorry! The file specified is unavailable!" << endl;
        return 0;
    }
    else
    {
        cout << "The file has been opened!" << endl;

        for (int a = 0; getline(infile, FILE[a]); a++);
        playerinfo.read(FILE);
        playerinfo.print_data();

    }
    printf("\n\n\n");
    system("pause");
}

我必须 提示用户输入和输出文件名。不要将文件名硬编码到您的程序中。  打开输入文件  读取每个玩家并将它们存储在 Player 对象数组中  跟踪阵列中的玩家数量  打开一个输出文件  将数组中的每个玩家连同分配所需的任何其他输出一起写入输出文件。  完成后记得关闭文件

【问题讨论】:

  • 你知道stringstream吗?
  • 没有。这只是一个基本的 C++ 程序,它读取文件,然后解析它并将其发送回输出文件。

标签: c++ file parsing getline


【解决方案1】:

输入中有 50 个字符串,但只有一个 playerinfo。它需要反过来——一个用于读取文件的字符串,以及 50 个playerinfos 来解析数据。

【讨论】:

  • 我还是有点困惑。我在 main 中有 for 循环,它只读取文件的每一行,然后将文件发送到函数,然后我可以解析它。有没有办法在函数内解析,这就是你的意思吗? for (int a = 0; getline(infile, FILE[a]); a++); playerinfo[50].read(FILE);
【解决方案2】:

使用流提取和插入运算符重载。例如看下面的代码,根据自己的需要修改。

#include <iostream>
using namespace std;

class player {
private:
    string first, last, position;
    float batave;
    int a;

public:
    friend std::istream & operator>>(std::istream & in, player & p) {
        in >> p.first >> p.last >> p.position >> p.batave;
        return in;
    }

    friend std::ostream & operator<<(std::ostream & out, const player & p) {
        out << p.last << ", " << p.first << ": " << p.position << " (" << p.batave << ")";
        return out;
    }
};

int main() {
    player p;
    while (cin >> p)          // or infile >> p;
        cout << p << endl;    // or outfile << p << endl;
}

查看DEMO

【讨论】: