如何读取具有特定格式的行)C++

how to read a line with an specific format) c++

本文关键字:定格 格式 C++ 何读取 读取      更新时间:2023-10-16

我在 c++ 中读取txt文件时遇到问题。

该文件由行组成,每行有 4 位数字,代表年份(例如 1900 年)和用"#"分隔的电影标题。

文件的格式为:编号#电影标题#电影标题#电影标题

线条示例:

1900#福尔摩斯困惑#魔法画

1904#不可能的航行

1918#斯特拉·马里斯#米奇#流沙#狗的生活#肩臂

我想读取每一行,将年份保存在int变量中,并将每个电影标题保存在字符串数组中。请帮忙。

这是我的(错误的)代码:

istream& operator >>(istream &is, Cronologia &crono){
    FechaHistorica fh;
    int anio;
    while(!is.eof()){
        char  c[1024];
        char  aux[4];
        is.read(aux,4);
        is.ignore('#');
        anio = atoi(aux);
        fh.setAnio(anio);
        cout << "n" << anio << endl;
        while(is.getline(c,1024,'#')){
            fh.aniadeEventoHistorico(c);
        }    
    }
    return is;    
}

FechaHistorica由以下人员组成:int n;字符串

数组

这种函数呢:

string test="1918#Stella Maris#Mickey#Shifting Sands";
vector<string> buffer;
size_t found = 0;
while ( found <= test.size() ){
    found = test.find('#')
    buffer.push_back(test.substr(0, found) );
    test.erase(test.begin(), test.begin()+(found+1) );
}

它返回像缓冲区一样的向量 = [1918, Stella Maris, ....],对于 txt 读数

ifstream f( path );
string line;
while (getline (f,line) ){
    // goes line by line, return line as string
}
f.close()
在你的

代码中is.ignore('#');是错误的。看这里。所以使用如下

if (iss.peek() == '#') {
    iss.ignore();
}

最后while(is.getline(c,1024,'#')){直到文件结束才结束。所以我认为,你先阅读整行,然后像下面这样处理它。

string line;
while(getline(is, line)){
    istringstream iss(line);
    char  c[1024];
    char  aux[4];
    iss.read(aux,4);
    if (iss.peek() == '#') {
        iss.ignore();
    }
    anio = atoi(aux);
    fh.setAnio(anio);
    cout << "n" << anio << endl;
    while(iss.getline(c,1024,'#')){
        cout << c << endl;
    }
}