c++中的Getline问题

Getline Issue in C++

本文关键字:问题 Getline 中的 c++      更新时间:2023-10-16

我有一个显示如下内容的文本文件:

John    Smith    21    UK
David   Jones    28    FRANCE
Peter   Coleman  18    UK

和我试图剥离每个单独的元素到一个向量数组。我已经尝试使用一个制表符分隔符的getline函数,但它存储每个元素。例如:

getline (f, line, 't');
records.push_back(line);

如何逐行分隔?其思想是执行搜索并输出相应的行。例如,搜索Jones将打印出第二行。

这是我目前所拥有的,但正如你所看到的,它没有给我想要的结果:

string sString;
string line;
string tempLine;
string str;
vector<string> records;
cout << "Enter search value: " << endl;
cin >> sString;
cout << "nSEARCHINGnn";
ifstream f("dataFile.txt");
while (f)
    {
    while(getline (f, tempLine))
    {
       getline (f, line, 't');
       records.push_back(line);
    }
    for(int i=0; i < records.size(); i++)
    {
       if(sString == records[i]) {
        cout << "RECORD FOUND" << endl;
        for(int j=0; j < records.size(); j++)
        {
            cout << j;
            cout << records[j] << "t";
        }
        }
    }
}
f.close();

第一个getline从输入中提取完整的一行。第二个命令从下一行提取一个字段。如果你想要恢复分解为字段的行,您应该这样做:

std::vector<std::vector<std::string>> records;
std::string line;
while ( std::getline( f, line ) ) {
    records.push_back( std::vector<std::string>() );
    std::istringsream fieldParser( line );
    std::string field;
    while ( std::getline( fieldParser, field ) ) {
        records.back().push_back( field );
    }
}

这将产生一个记录向量,每个记录在其中一个场的向量。更常见的情况是,您希望使用结构体对于记录,并在行上做更多的解析,例如:

struct Field
{
    std::string firstName;
    std::string lastName;
    int age;
    std::string country;
};
std::vector<Field> records;
std::string line;
while ( std::getline( f, line ) ) {
    std::istringsream fieldParser( line );
    Field field;
    fieldParser >> field.firstName >> field.lastName >> field.age >> field.country >> std::skipws;
    if ( !fieldParser || fieldParser.get() != EOF ) {
        //  Error occurred...
    } else {
        records.push_back( field );
    }
}

(只有当所有字段都不能工作时,这个简单的东西才会工作包含空白。但是扩展起来很简单)

你正在把getline变成tempLine,它吃掉了一整行,然后你在循环中也做了一个不同的getline。这就是为什么它不起作用的一个重要部分——你只是简单地扔掉了包含大量数据的tempLine