一个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

本文关键字:定位 txt 数字 文件 输出 程序 C++ 用于 输入 一个      更新时间:2023-10-16

使用此代码,我可以将文本文件的所有编号提取到另一个文本文件中。但是我想要实现的是,我想输入要提取的数字的位数,然后只提取那些包含 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