C++ getline multiple variable types using comma as delimiter

試著忘記壹切 提交于 2019-12-06 13:47:07

问题


I'm trying to do a home work assignment which requires data fro a txt file to be read in to variables. The file has this on each line "surname, initials, number, number". I have got the get line working partially using the following code.

    ifstream inputFile("Students.txt");
string line;

string Surname;
string Initial;
int number1, number2;

while (getline(inputFile, line))
{
    stringstream linestream(line);

    getline(linestream, Surname, ',');
    getline(linestream, Initial, ',');
    getline(linestream, number1, ',');
    getline(linestream, number2, ',');

    cout << Surname << "---" << Initial << "-" << number1 << "-" << number2 << endl;

}

This throws a compile error, but if I declare number1 and number2 as strings it works fine. So my question is, do I have to getline as a string then convert to an int variable or is there a better way?


回答1:


Yes, the second parameter of getline function must be a string by definition and it will contain your extracted string. Simply declare number1 and number2 as string and then convert them to Integer with stoi() (C++11) or atoi() function :

string strNumber1;
string strNumber2;
getline(linestream, strNumber1, ',');
getline(linestream, strNumber2, ',');
int number1 = stoi(strNumber1);
int number2 = atoi(strNumber2.c_str());

Hope this helps




回答2:


std::getline takes as a first parameter an object of std::basic_istream. It won't work for any other object.

What I did was use the csv_whitespace class to add a comma as a delimeter. For example:

class csv_whitespace
    : public std::ctype<char>
{
public:
    static const mask* make_table()
    {
        static std::vector<mask> v(classic_table(), classic_table() + table_size);
        v[','] |= space;
        v[' '] |= space;
        return &v[0];
    }

    csv_whitespace(std::size_t refs = 0) : ctype(make_table(), false, refs) { }
};

int main()
{
    std::ifstream in("Students.txt");
    std::string line;

    std::string surname;
    std::string initial;
    int number1, number2;

    while (std::getline(in, line))
    {
        std::stringstream linestream(line);
        linestream.imbue(std::locale(linestream.getloc(), new csv_whitespace));

        getline(linestream, surname, ',');
        getline(linestream, initial, ',');

        linestream >> number1 >> number2;
    }
}


来源:https://stackoverflow.com/questions/19107439/c-getline-multiple-variable-types-using-comma-as-delimiter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!