一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
A C++ program to output all the numbers in a .txt file with a specific number of digits when the number of digits is entered
使用此代码,我可以将文本文件的所有编号提取到另一个文本文件中。但是我想要实现的是,我想输入要提取的数字的位数,然后只提取那些包含 no 的数字。我输入的数字数。 提前谢谢你。
#include <iostream>
#include <fstream>
using namespace std;
bool isStop(char c);
int main()
{ fstream fin;
fstream fout;
string s;
char a,b=' ';
fin.open("TheFileThatContainsData.txt", ios::in);
fout.open("Numbers.txt", ios::out);
while(fin.get(a))
{ if(isdigit(a) || isStop(b))
{ s+=a;
while(fin.get(a) && isdigit(a))
{ s+=a;
}
if(isStop(a) || fin.eof())
{ for(int i=0;i<s.length();i++)
{ fout.put(s[i]);
}
fout.put('n');
}
}
s.clear();
b=a;
}
fin.close();
fout.close();
return 0;
}
bool isStop(char c)
{
return (c==' ' || c=='.' || c==',' || c=='(' || c==')' || c=='!' || c=='?' || c=='n');
}
考虑到你的代码,我建议你读一本关于编程"良好实践"的好书,并逐步完成。
下面是一个代码,可以满足你的要求:
#include <iostream>
#include <sstream>
#include <cctype>
int main()
{
using std::string;
using std::stringstream;
string input="1 123 . 12 12 12345 1 12 123 123456 123 123 1234";
stringstream fin(input); //replace by file stream if needed
stringstream fout; // replace by file stream if needed
constexpr size_t digitsFilter=2;
while (fin.good())
{
// Trim non-digits
while(fin.good() && !std::isdigit(fin.peek()))
{
fin.get();
}
// Get number
unsigned number=0;
fin >> number;
// Filter by length
if (std::to_string(number).size() == digitsFilter)
{
fout << number << std::endl;
}
}
std::cout << fout.rdbuf();
return 0;
}
https://onlinegdb.com/HJL2h5D3I
相关文章:
- 如何将 txt 文件中的行分隔为组件C++
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 一种在C++中读取TXT配置文件的简单方法
- 如何修复此iFile以将.txt输出到控制台
- 无法打开.txt文件
- CMakeLists.txt中的命名空间表示法
- Arduino从Txt读取整数
- 如何使用CLion在Mac上创建一个新的.txt文件
- 重新定位图像时如何前进到下一个内存块
- 如何拆分文件中.txt字母并使用c ++使用数组进行扑克?
- 使用fstream对txt文件中的数字进行循环
- Visual Studio在尝试读取resource.txt文件时崩溃
- 更正 CMakeList.txt 用于谷歌测试的文件?
- 如何从txt文件中读取多个不同长度的数组?
- 在一次迭代中从 txt 文件中读取多行
- 流填充字符的默认定位
- 将生成文件转换为 CMakeLists.txt等效项
- 使用循环将多行写入.txt
- CMake 错误"源似乎不包含 CMakeLists.txt",路径/库连接问题
- C++/autoconf 等效于文档库要求.txt的要求是什么?