c++ - 仅打印那些包含 2 位数字的字符串
问题描述
仅打印那些包含 2 位数字的字符串
“myFile.txt 中的文本是
{粉色双跳34
上升的青蛙 2
执行代码 11
不错 4}"
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <algorithm>
int main()
{
std::string path = "myFile.txt";
std::ifstream de;
de.open(path);
if (!de.is_open()) {
std::cout << "nah";
}
else {
std::cout << "file is opened";
std::string str;
while (!de.eof()) {
std::getline(de, str);
for (int i = 0; i < str.length(); i++) {
int aa = 10;
if (str[i] > aa) {
str = "0";
}
}
std::cout << str << "\n\n";
}
}
}
我究竟做错了什么?如何检查字符串中是否有 2 位数字?
解决方案
你可以使用stoi
如下:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::ifstream inp("test.txt");
std::string word;
std::vector<std::string> listOfTwoDigitStrings;
while(inp>>std::ws>>word) {
if(word.length() == 2) {
int num = std::stoi(word);
if(num >= 10 && num <= 99) {
listOfTwoDigitStrings.push_back(word);
}
}
}
for(const auto& word: listOfTwoDigitStrings) {
std::cout<<word<<' ';
}
std::cout<<'\n';
return 0;
}
有输出
34 11
当test.txt
包含
{粉色双跳34
上升的青蛙 2
执行代码 11
不错 4}"
PS:当您在寻找字符串时,只需读取字符串而不是行,然后从该行读取字符串。读取字符串只是让它变得更简单,因为它归结为只是缩小到 2 位数的字符串,然后只是验证它们是否是数字。此外,如评论中所述,请避免使用!file.eof()
代码。
推荐阅读
- c - 在由结构组成的树上使用 qsort() 时,我没有收到返回的排序数组
- dart - Flutter - 将图像设置为材质的背景
- excel - 如何在 excel 中使用多个 vlookup 标准?
- swift - 无法使用 iOS 应用程序读取蓝牙服务 (BLE) 中的用户定义特征
- excel - 创建数据透视表不适用于新的 Excel 版本
- javascript - 有没有办法将服务器端 JS 嵌入 HTML(如 PHP)?
- angular - 检测到循环依赖中的警告:
- c# - 如何使用“编辑器协程”包在编辑器中启动协程?
- zeromq - 使用 zmqpp 进行零拷贝消息传递
- linux - 等效于 head/tail 命令以显示头/尾或一行