从文本文件c++中加载结构体向量的奇怪问题
Odd issue with loading vector of structs from text file C++
我目前正试图将数据从文本加载到结构体向量中。它在第一行工作,然后死亡并打印零,原因我不知道。
我的代码是下面,它是相当简单的,以及我正在阅读的文本文件。我很感激一些帮助,因为我不明白为什么它这样做。
#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++;
}
相关文章:
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 添加存储在向量中的大整数的函数出现问题
- C++ 继承向量问题(无限循环+在其他类中使用向量的问题)
- SWIG c++到python:向量问题
- 向量问题,如何删除向量中的数组?
- 向量问题,也许有点手
- ndk中的标准与cpp向量问题
- 从数据文件到多维向量问题
- C++:向量问题的向量
- 类向量 c++ 问题
- 特征向量问题
- C++std::向量问题
- 结构中的向量问题
- C++类向量问题
- 向量的向量问题
- 获取索引和元素-向量问题
- 搜索或发现向量问题内部
- C++向量问题;通过引用传递内容
- 几个c++向量问题
- 指向包含向量问题的实例类的指针<int>