尝试将字符串变量转换为bool会导致“ true”和“ false”都等于0

时间:2019-04-18 23:15:25

标签: c++ if-statement ifstream

我是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=TRUEendg=FALSE),wildendanger均为0。

我将非常感谢您的帮助。谢谢。

2 个答案:

答案 0 :(得分:4)

这里:

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>

答案 1 :(得分:1)

首先,如果您“使用命名空间标准”,通常被认为是不好的做法。 其次,如果要将传递的变量更改为函数,请将该变量作为参考传递。像这样:

bool& newVar
相关问题