C++ ifstream,加载时出现问题,";"
C++ ifstream, issue loading with ";"
int a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}
所以这是我一直在看的代码,但我遇到了一个问题,因为我的字符串之间没有空格,它们有";">
我的代码:
void load(string filename){ // [LOAD]
string line;
ifstream myfile(filename);
string thename;
string thenumber;
if (myfile.is_open())
{
while (myfile >> thename >> thenumber)
{
cout << thename << thenumber << endl;
//map_name.insert(make_pair(thename,thenumber));
}
myfile.close();
}
else cout << "Unable to open file";
}
[Inside the txt.file]
123;peter
789;oskar
456;jon
我现在得到的是"thename"为123;peter和"thenumber"为789;oskar。我希望"thename"作为peter,"thenumber"作为123,这样我就可以正确地将其插入到我的地图中,如何?
infile>> 从 for a 的合格类型文件中读取。在你的例子中,a 是 int,所以">>"期望找到一个 int。在您的代码中,myfile>>名称>>数字都是字符串类型,因此它们期望文件中的字符串类型。问题是字符串包含";",因此变量名称将占用所有行,直到找到(换行符(。
在您的代码中
std::string thename, thenumber;
char delimeter(';'); //It is always '-' is it?
std::getline(std::cin, thename, delimeter);
std::getline(std::cin, thenumber);
数字也将是字符串类型。要将数字转换为 int:
std::istringstream ss(thenumber);
int i;
ss >> i;
if (ss.fail())
{
// Error
}
else
{
std::cout << "The integer value is: " << i;
}
return 0;
以
这种格式读取文件相当简单。 您可以将std::getline
与不同的分隔符一起使用,以告知它在哪里停止读取输入。
while(getline(myfile, thenumber, ';')) // reads until ';' or end of file
{
getline(myfile, thename); // reads until newline or end of file
map_name.insert(make_pair(thename,thenumber));
}
您必须输入一个字符串,然后将其拆分以获取名称和数字
....
#include <string>
#include <sstream>
#include <vector>
std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
....
void load(string filename){
..........
if (myfile.is_open())
{
while (myfile >>whole)
{
std::vector<std::string> parts = split(whole, ';');
name = parts[0];
number = parts[1];
}
}
相关文章:
- 尝试使用 Ifstream 打开.txt文件时C++问题
- 使用 c++ ifstream 读取文本文件问题
- 将 istream 转换为 ifstream 时将 std::cin 传递到参数时出现问题
- 关于使用ifstream在C 中确定文件是否存在的问题
- 从Windows任务栏执行时ifstream问题
- 试图使用cmake打开ifstream的文件的问题
- 在 ifstream 上调用 clear() 有问题吗?
- C++:ifstream getline 问题交叉编译到 OpenWRT 发行版中
- 使用ifstream的模板函数有什么问题
- 将文件的常量字符* 地址传递给 ifstream 对象的问题
- 在C++中使用ifstream打开文本文件时遇到问题
- 读取文件(ifstream)和写入文件(ofstream)-编码问题
- 在 qt 中使用 ifstream 打开文件时出现问题
- 正确从 ifstream 获取值时出现问题
- 使用 ifstream 打开文件时遇到问题
- 在 C++ 中使用 ifstream 时遇到问题
- ifstream 对象的 .read() 问题 *char
- 我的ifstream方法出了什么问题
- C++ ifstream,加载时出现问题,";"
- Ifstream在编译器问题