目前尝试从文本文件中存储一些信息,文本文件的格式为数字/文本/文本/数字,我想分别将它们保存为int,string,string和float。在文件中它们实际上用/分隔,因此文本文件的示例可能看起来像173 / hello / goodbye / 13.4
这是我到目前为止的代码
int main(){
string menuname;
int a;
float d;
string b;
string c;
bool error = false;
ifstream openFile;
do{
cout << "Please enter the name of the menu you would like to open: ";
cin >> menuname;
menuname += ".txt";
openFile.open(menuname.c_str());
if(openFile.fail()){
cerr << "Unable to open file, please re-enter the name.\n";
error = true;
}
}while(error == true);
openFile >> a;
openFile >> b;
openFile >> c;
openFile >> d;
cout << itemno << category;
}
我并不是100%确定是什么导致了这个问题,但我觉得它可能与字符串有关,好像我只是使用openFile >> a;
与正确显示的下一个3,但是在添加openFile >> b;
之后,它会显示整行,而不仅仅是旁边的单词/短语。
答案 0 :(得分:0)
答案 1 :(得分:0)
使用getline()并添加分隔符'/'可以解决此问题,但是当您使用它来读取文本文件时,默认情况下将读取的值将是string类型。您必须使用cstdlib,atoi()函数将int转换为int并将其转换为程序所需的函数,并将atof()用于double / float。请参阅以下代码:
#include<iostream>
#include<fstream>
#include<cstdlib>
using namespace std;
int main()
{
string menuname;
string a, b, c, d;
bool error = false;
ifstream openFile;
do
{
cout << "\n Please enter the name of the menu you would like to open: ";
cin >> menuname;
menuname += ".txt";
openFile.open(menuname.c_str());
if (openFile.fail())
{
cerr << "\n Unable to open file, please re-enter the name.\n";
error = true;
}
} while (error == true);
cout << endl;
getline(openFile, a, '/');
getline(openFile, b, '/');
getline(openFile, c, '/');
getline(openFile, d, '/');
int aNum = atoi(a.c_str());
float dNum = atof(d.c_str());
cout << " " << a << " " << b << " " << c << " " << d;
cout << "\n Trying to add an int and a double: " << aNum + dNum;
return 0;
}
我创建的文本文件包含: 123 /你好/再见/ 12.3
将输出:
123 Hello Goodbye 12.3
Trying to add an int and a double: 135.3
我也是C ++的新手,如果有人在我编辑的代码中发现错误,请纠正我。
答案 2 :(得分:0)
通常只应在提取对象时使用提取运算符。如果你正在做的事情让我知道,我会编辑这个答案。
您可以使用尾随分隔符来简化输入,然后可以对每个输入使用getline
。但是因为它仍然可以解决你的问题:
openFile >> a; // There is no leading delimiter, and the delimiter is not numeric therefore we can simply use the extraction operator
openFile.ignore(numeric_limits<streamsize>::max(), '\n'); // We must also purge the delimiter
getline(openFile, b, '/'); // This will include white spaces in b
getline(openFile, c, '/'); // This will include white spaces in c
openfile >> d; // Again using the extraction operator, but because there is no trailing delimiter no need to purge
这种提取方法是非常容错的,事实上我认为它唯一无法处理的是转义分隔符。如果您需要支持,请告诉我,但在那时我倾向于使用regex_token_iterator