getline无法使用fstream
getline not working with fstream
我正试图使用一个文本文件来初始化一个结构,该结构将用于初始化2d向量,是的,我知道这很复杂,但最终会有很多数据需要处理。问题是getline,我在其他代码中也用过这种方式,但由于某种原因,它拒绝在这里工作。我不断收到一个参数错误和模板错误。如有任何提示,我们将不胜感激。
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
const int HORIZROOMS=10;
const int VERTROOMS=10;
const int MAXDESCRIPTIONS=20;
const int MAXEXITS=6;
struct theme
{
string descriptions[MAXDESCRIPTIONS];
string exits[MAXEXITS];
};
void getTheme();
int _tmain(int argc, _TCHAR* argv[])
{
getTheme();
vector<vector <room>> rooms(HORIZROOMS, vector<room>(VERTROOMS));
for (int i=0; i<HORIZROOMS; i++)
{
for (int j=0; j<VERTROOMS; j++)
{
cout<<i<<" "<<j<<" "<<rooms[i][j].getRoomDescription()<<endl;
}
}
return 0;
}
void getTheme()
{
theme currentTheme;
string temp;
int numDescriptions;
int numExits;
ifstream themeFile("zombie.txt");
getline(themeFile, numDescriptions, ',');
for (int i=0; i<numDescriptions; i++)
{
getline(themeFile, temp, ',');
currentTheme.descriptions[i]=temp;
}
getline(themeFile, numExits, ',');
for (int i=0; i<numExits; i++)
{
getline(themeFile, temp, ',');
currentTheme.exits[i]=temp;
}
themeFile.close();
}
std::getline
用于从流中提取到std::string
。当提取到numDescriptions
和numExits
时,实际需要的是operator>>
。例如,
themeFile >> numDescriptions;
这将在以下,
自动停止提取。但是,如果您不希望它出现在下一个std::getline
提取中,则需要跳过此逗号:
themeFile.ignore();
或者,您可以有一个std::string numDescriptionsString
,用它来执行std::getline(themeFile, numDescriptionsString, ',')
,然后用std::stoi
:将该std::string
转换为int
getline(themeFile, numDescriptionsString, ',');
numDescriptions = std::stoi(numDescriptionsString);
不过我想说这更难看。
相关文章:
- Seg Fault Issue C++ (file IO / getline)
- 在fstream期间忽略空行
- 当用户键入分隔符时,停止getline()输入
- getline() 的原型/库是什么;
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 使用fstream对txt文件中的数字进行循环
- 如何在 c++ 中使用 ',' 作为 getline 分隔符
- 错误:调用'getline'没有匹配函数
- 如何在 c++ 中使用 getline 从文件中读取字符串?
- std::getline with std::fstream
- fstream getline()未经治疗的例外
- C++ fstream getline parameters
- fstream的getline()工作了一点...然后中断
- 在类中使用fstream getline()函数
- fstream中多个get()和单个getline()之间的理论性能差异
- std::getline函数(fstream _Lock())出错
- 遇到getline、fstream、作用域不一致的问题
- 在同一个fstream对象上使用getline的两个函数
- 使用getline fstream读取文件
- getline无法使用fstream