C++中文件逗号后的股票值
Stock values after comma from a file in C++
我试图检测并忽略从同一行到股票值的逗号。
我尝试了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");
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- VSCode C++调试文件名中包含中文字符的文件时插件损坏
- 使用fstream用中文/日文编写的文本,无法正确读取文件
- 从C/C++中的.csv文件中读取中文字符
- 如何使用PoDoFo的"podofotxtextract"(C++)样本从PDF文件中读取中文文本
- 当读文件为英文时,对文本文件的写入显示为中文