c++ - 字符串成员不适用于由分隔符分隔的文件中的字符串
问题描述
此代码应该打印字符串的一部分,它是最后一个字符,但是 delimiter(:) 之后的第二部分只打印字符串而不是字符。为什么它不起作用,我该如何解决?
代码:
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string info;
void PrintTextFile(){
ifstream myfile("example.txt");
if(myfile.is_open()){
while (getline(myfile, info, ':')){
cout << info << " " << info.back() << "\n";
}
myfile.close();
}
else {
cout << "Unable to open file.";
}
}
int main(int argc, char *argv[]) {
PrintTextFile();
return 0;
}
示例.txt:
Left1:Right1
Left2:Right1
Left3:Right3
我的输出:
Left1 1
Right1
Left2 2
Right2
Left3 3
Right3
预期输出:
Left1 1
Right1 1
Left2 2
Right2 2
Left3 3
Right3 3
解决方案
这里的问题是,当您为其提供自己的分隔符时,getline
它会停止使用换行符作为分隔符。这意味着在您读入的第一个循环中Left1:
,丢弃:
andinfo
留下Left1
. 您再次阅读的第二次迭代,直到您看到 an:
所以您读入Right1\nLeft2:
,丢弃:
which leave info
with Right1\nLeft2
。
您需要做的是读取整行,然后使用字符串流将其解析出来
while (getline(myfile, info)){
stringstream ss(info)
while (getline(ss, info, ':') // this works now because eof will also stop getline
cout << info << " " << info.back() << "\n";
}
或者,既然您知道您只需要两个值,请通过阅读该行的每个部分来获取它们,例如
while (getline(myfile, info, ':')){
cout << info << " " << info.back() << "\n";
getline(myfile, info);
cout << info << " " << info.back() << "\n";
}
推荐阅读
- javascript - 带有 Node JS Express 和 PostgreSQL 的数据表
- python - 我有一个从 Python 运行外部软件的功能,我如何在并行处理器上运行它?
- javascript - 如何在 React js 中显示或隐藏带有过渡动画的组件
- php - Cakephp 数据库会话
- excel - Excel if 语句 - 如果不是这个或不是那个 - 这样做
- python - 如何在csv文件中将一行拆分为多行?
- python - Python Selenium _ 与 iframe 中的“li”元素交互
- spring - 是否可以跳过我不需要的端点或者这被认为是一种不好的做法?
- conditional-formatting - 如何在 TiddlyWiki 列表项中进行条件文本格式化?
- sqlite - 通过 Sequelize 加载 sqlite 扩展