我是C ++的新手,我可能会遗漏一些未成年人的东西,但是他们已经盯着这个太长时间,并且真的很感激一些帮助。
我正在进行一项任务,程序从CSV文件中读取数据。首先,我使用getline()将所有数据导入为字符串,因为这是我知道的唯一方法。导入后,我想(正在尝试)将带有“TRUE”和“FALSE”的字符串变量转换为bool类型。
CSV文件包含:
name,color,age,wild,home,endagered
Foo,brown,3,TRUE,Malaysia,FALSE
以下是我的代码。我意识到这可能是非常低效的,但我正在学习,所以...它就是它的本质。
这是转换函数(它应该能够处理文件中的错误):
void stringBool(const string & temp, bool newVar)
{
const string fc = "FALSE";
const string fl = "false";
const string tc = "TRUE";
const string tl = "true";
try {
if (temp==fc || temp==fl)
{
newVar = false;
}
else if (temp==tc || temp==tl)
{
newVar = true;
}
else
{
throw temp;
}
} catch (string e) {
cout << newVar << " = " << e << " is not in the correct format. Check your file and try again." << endl;
exit(1);
}
};
这是类的读入成员函数。如果重要的话,它是派生类中的虚函数。 (不想用不太相关的代码淹没帖子,但如果你想看到它,请告诉我。)
void readIn(std::string filename)
{
ifstream myFileStream(filename);
//Error if file fails to open
if(!myFileStream.is_open())
{
cout << "File failed to open" << endl;
exit(1);
}
//Temporary strings to import
string ag, wld, endg;
string myString, line;
//Read in data
getline(myFileStream, line); //Skip first line
while(getline(myFileStream, line))
{
stringstream ss(line);
getline(ss, name, ',');
getline(ss, color, ',');
getline(ss, ag, ',');
getline(ss, wld, ',');
getline(ss, home, ',');
getline(ss, endg, ',');
}
myFileStream.close();
//Convert variables from string to appropriate form
stringBool(wld, wild);
stringBool(endg, endanger);
age = stoi(ag);
//Print variables to check
cout << name << endl << color << endl << age << endl << wild << endl << home << endl << endanger << endl;
//Print temporary variables
cout << wld << endl;
cout << endg << endl;
};
当我实际调用main中的函数时,输出是:
Foo
brown
3
0
Malaysia
0
TRUE
FALSE
所以即使数据输入正确(字符串是正确的 - wld=TRUE
和endg=FALSE
),wild
和endanger
都是0。
我真的很感激任何帮助。谢谢。
这里:
void stringBool(const string & temp, bool newVar)
{
你按价值通过newVar
。如果你想改变newVar
来改变相应函数中的值,它应该是一个引用:
void stringBool(const string & temp, bool& newVar)
{
或者,让它返回值:
bool stringBool(const std::string& temp) {
if(temp == "true" || temp == "TRUE") return true;
if(temp == "false" || temp == "FALSE") return false;
throw std::invalid_argument("Input '" + temp + "' should be either 'true' or 'false'");
}
你可以通过加入std::invalid_argument
找到<stdexcept>
首先,如果你“使用命名空间std”,这通常被认为是一种不好的做法。其次,如果要将传入的变量更改为函数,请将该变量作为参考传递。像这样:
bool& newVar