C++中文件逗号后的股票值

Stock values after comma from a file in C++

本文关键字:中文 文件 C++      更新时间:2023-10-16

我试图检测并忽略从同一行到股票值的逗号。

我尝试了getline的3参数,但没有成功。我也试过迭代器。

我的文本文件包含以下值:

Bob Jackson,25,Sick
Eric Smith,99,Deceased
Alice Vanderlend,16,Healthy

在下面的代码中,我对我的失败尝试进行了评论。。。

string str,fn, ln, age, sta;
    ifstream input("text.txt");

    while (getline(input, str)) 
    {   
        /*for ( string::iterator it=str.begin(); it!=str.end(); ++it)
        {
            if ((*it) == ','){continue;};
        }*/
        //string vir;
        istringstream iss(str);
        //if(!(getline(input, vir, ','))){break;}
        iss >> fn >> ln >> age >> sta;
        cout 
        << "First Name: " << fn 
        << "nLast Name: " << ln 
        << "nAge: " << age 
        << "nStatus: " << sta << endl  << endl;
    }

我期望得到的输出是

First Name: Bob
Last Name: Jackson
Age: 25
Status: Sick
...

相反,我得到了:

First Name: Bob
Last Name: Jackson,25,Sick
Age:
Status:
...

如何忽略逗号来储存下一个值?

如下声明一个伪变量:

char comma;

并读出额外的逗号:

iss >> fn >> ln >> comma>> age >> comma >> sta;

而不是

iss >> fn >> ln >> age >> sta;

在将字符串发送到std::stringstream:之前,可以用空格替换字符串中的所有逗号

std::replace(str.begin(), str.end(), ',', ' ');

用这个替换读取代码

iss>>fn;
getline( iss,ln, ',');
getline( iss,age, ',');
getline(iss,sta, ',');

getline的第三个参数是分隔符。

只要将年龄更改为int。。。假设这对您以后更方便,并且它的解析将在逗号处停止,但您必须显式处理姓氏字符串。。。

char c;
if (iss >> fn && std::getline(iss, ln, ',') && iss >> age >> c >> sta && c == ',')
     ...parsed ok - use vars...
else
    throw std::runtime_error("invalid input");