当文本文件位于行尾时如何检测"0"?
How to detect '0' when it comes at the end of the line for a text file?
我正在扫描一个文本文档,它的格式是这样的:
3 10
1阿拉伯数字
阿拉伯数字
1
3
1
1
1阿拉伯数字
阿拉伯数字
顶部的前两个整数分别表示候选人的数量和票数。我很难检测到票数的字符串"10"
由于我正在使用 c++,到目前为止我已经尝试这样做:
string line;
int candidateTally;
int voteTally;
ifstream file("votes.txt");
//detect the candidate tally "3"
getline(file, line);
candidateTally = atoi(line.c_str());
cout << candidateTally << endl;
//output the candidate tally "10" but it's only outputting "1"
getline(file, line);
cout << line;
我不太确定如何拿起 0 的第二个字符以获得完整的"10"字符串似乎 getline 函数在拾取 0 之前切断,因为这可能代表""字符?我想让它检测"0"并将其包含在带有"1"的字符串中,以便我可以将其转换为它应该是 10 的 int。
我该如何解决这个问题?
问问自己getline
是做什么的...是的,它有一条线。
所以第一个调用"获取"整行"3 10",第二个调用"获取文件中的下一行:"1"
应使用 >>
运算符从文件中读取传入值。这也将消除弄乱atoi()
和字符指针的需要。
请改用以下内容:
int candidateTally;
int voteTally;
ifstream file("votes.txt");
//detect the candidate tally "3", and the vote tally "10".
file >> candidateTally >> voteTally;
cout << candidateTally << endl;
cout << voteTally << endl;
operator>>
忽略空格。它的第一个调用(file >> candidateTally
)将"吃掉"3",第二次调用(>> votetally
)将跳过空格,然后拾取"10"。精度可以在这里阅读,但细节很难阅读。
如果您要获得候选人和选票数的行,则没有理由使用atoi
:
std::string line;
int candidateTally;
int voteTally;
std::ifstream file("votes.txt");
if (std::getline(file, line))
{
std::istringstream iss(line);
iss >> candidateTally >> voteTally; // you should also add error handling here
// ...
}
else
{
// handle the error here
}
相关文章:
- 使用CMake检测支持的C++标准
- 当套接字连接断开时检测C/C++Unix
- C/C++预处理器是否可以检测一些编译器选项
- WMI检测进程创建事件-c++
- 基于树莓pi的tensorflow lite量化ssd目标检测
- 下面是我为检测链接列表中的循环而制作的代码
- 落砂模拟碰撞检测C++和SFML
- 我可以检测和更改 gcc/g++ 中结构的当前数据对齐设置吗?
- 为什么C++编译器没有检测到正确声明的类?
- 检测win32服务创建和删除的最佳方法
- 正在LLVM中检测整数比较条件
- 如何在鼠标挂钩过程中检测拖动
- 位移操作和位掩码未检测到重复字符
- 检测 COFF 对象文件中C++内联符号
- qmake:检测目标位宽(32 位或 64 位)
- 增强精神解析器规则以检测语句中的特殊结尾
- 用于C++的静态二进制检测或二进制重写工具和框架
- Tensorflow对象检测在Python和C++(OpenCV)之间有不同的结果
- 0x00363A09处出现未处理的异常,堆栈cookie检测代码检测到基于堆栈的缓冲区溢出
- CRT内存泄漏检测未检测到内存泄漏