C ++ getline使用逗号作为定界符的多个变量类型 [英] C++ getline multiple variable types using comma as delimiter

查看:721
本文介绍了C ++ getline使用逗号作为定界符的多个变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行家庭作业,这需要将txt文件中的数据读入变量中.该文件在每行姓氏,缩写,编号,编号"上都有此名称.我使用以下代码使get行部分工作.

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;

}

这会引发编译错误,但是如果我将number1和number2声明为字符串,则可以正常工作.所以我的问题是,我必须先将getline作为字符串然后转换为int变量,还是有更好的方法?

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?

推荐答案

是的,根据定义,getline函数的第二个参数必须是字符串,并且它将包含您提取的字符串.只需将number1和number2声明为字符串,然后使用stoi()(C ++ 11)或atoi()函数将它们转换为Integer即可:

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());

希望这会有所帮助

这篇关于C ++ getline使用逗号作为定界符的多个变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆