从文本文件c++中加载结构体向量的奇怪问题

Odd issue with loading vector of structs from text file C++

本文关键字:向量 问题 结构体 加载 文本 文件 c++      更新时间:2023-10-16

我目前正试图将数据从文本加载到结构体向量中。它在第一行工作,然后死亡并打印零,原因我不知道。

我的代码是下面,它是相当简单的,以及我正在阅读的文本文件。我很感激一些帮助,因为我不明白为什么它这样做。

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <string>
using namespace std;
struct Symbol
{
    int type;
    string name;
};
int main()
{
    /************ VARS ***************/
    string line;
    int line_count;
    int increment;
    /************ Vector of Symbols ***************/
    vector<Symbol> symbols;
    cout << "Opening file..." << endl;
    ifstream file;
    file.open("symbols.txt");
    if(!file)
    {
        cout << "System failed to open file.";
    }
    while(file)
    {
        Symbol temp;
        getline(file, temp.name);
        file >> temp.type;
        symbols.push_back(temp);
        increment++;
    }
    //Just to test and see if its loading it correctly...
    for(int i = 0; i < symbols.size(); i++)
    {
                    cout << symbols[i].name << endl;
                    cout << symbols[i].type << endl;
    }
}
输入文件:

count
2
num
2
myFloat
4
myDouble
5
name
6
address
6
salary
5
gpa
4
gdp
5
pi
5
city
6
state
6
county
6
ch
0
ch2
0
ID
1
studentID
1
max
3
max2
3
greeting
6
debt
5
age
2
输出:

Opening file...
count
2
0   

您正在使用的循环没有考虑到最后一次格式化提取在流中留下换行符的事实。当std::getline()第二次运行时,它将找到换行符并停止提取字符(因此没有向temp.name插入任何字符)。流将std::ios_base::failbit设置为流状态,任何进一步的输入尝试都将失败。

必须清除换行符。您可以使用std::ws来完成此操作。此外,您还可以按照如下方式重构循环:

for (Symbol temp;
     std::getline(file >> std::ws, temp.name) && file >> file.type; )
{
     symbols.push_back(temp);
     increment++;
}

进一步看,我注意到你甚至不需要std::getline()。使用operator>>():

提取
for (Symbol temp; file >> temp.name >> temp.type; )
{
     symbols.push_back(temp);
     increment++;
}