在 c++ 中读取格式化的文本文件

Formatted text file reading in c++

本文关键字:文本 文件 格式化 读取 c++      更新时间:2023-10-16

这是文件。

R: 10
Steve Abrew 90 80 84 76
David Nag 93 87 90 80
Mike Black
Andrew Van Den 90 88 95 85
Chris Smith 86 74 90
Dennis Dudley 74 76 77 83
Leo Rice 95 75
Fred Flinstone 73 67 78 72
Dave Light 89 71 91 89
Hua Tran Du 81 79 80

我想从文件中读取这些内容,并分别为字符创建一个变量,为整数创建一个变量。但做不到..

这是我的代码:

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main(int argc,char* argv[])
{
ifstream inFile;
inFile.open(argv[1]);
if(!inFile)
{
cerr<<"Couldn't find the file";
return -1;
}
string data;
getline(inFile,data,'');
cout<<data<<"n";
return 0;
}

输出现在与文件相同。但是一切都保存在字符串数据中。但是现在我如何将名称和 int 与该字符串分开?

非常感谢,如果你帮忙:)

好的,我得到了格式。

我可以告诉你怎么做。在此之前,请创建一个名为 N 的 int 变量,以及一个deque<string>型容器Charactersdeque<deque<int>>型容器Data。(当然要做#include <deque>)(还有#include <sstream>#include <string>

首先,输入"R:"部分 -> inFile >> temp;
其次,输入将收集多少行数据> inFile >> N;
第三,输入数据。

for(int i = 0;i<N;i++)
{
    string Fn, Ln;
    inFile >> Fn >> Ln;
    Characters.push_back(Fn+" "+Ln); //name
    string A;
    getline(inFile,A);
    stringstream ss(A);
    int W;
    deque<int> TempData;
    while(ss>>W)
    {
        TempData.push_back(W);
    }
    Data.push_back(TempData);
}

现在,名称位于Characters容器中,其数据位于Data容器中!