获取线和分析数据

Getline and parsing data

本文关键字:数据 获取      更新时间:2023-10-16

我的程序需要从包含不超过 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("nnn");
    system("pause");
}

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

输入

中的行有 50 个字符串,但只有一个playerinfo 。 它需要相反 - 一个字符串用于读取文件,以及 50 playerinfo 秒的数据解析。

使用流提取和插入运算符重载。例如,请参阅下面的代码并根据您的需要进行修改。

#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;
}

观看演示