如何在C++中以字符串形式递增数字
How can I increment a number in a string form in C++?
好的,我正在学习C++。我想看看有多少文件存在的银行帐户程序为类。我的方法是运行一个循环来运行,并尝试打开"0000000001.txt",看看它是否有效,然后打开"0000000002.txt",以此类推。困难的部分是数字有前导零(在".txt"之前总共需要10位数字。
double num_of_accounts() {
double number_of_accounts = 0;
double count = 0;
double testFor = 0000000000;
ofstream ifile;
string filename = "0000000000";
for (count = 0; 0 < /*MAX_NUMBER_OF_ACCOUNTS*/ 5; count++){
ifile.open(filename + ".txt");
if (ifile) { number_of_accounts++; }
// I would like to increment the number in the filename by 1 here
} // END of for (count = 0; 0 < MAX_NUMBER_OF_ACCOUNTS; count++){
return number_of_accounts;
}
或者可以将双精度设置为10位数,然后使用to_string()转换为字符串?我试着在谷歌上搜索,但我不知道我是否用错了关键词。
如果有帮助的话,这是在win控制台上。
感谢
您应该使用流来实现这一点。参见此示例:
#include <fstream>
#include <iomanip>
#include <sstream>
#include <iostream>
for(unsigned long int i = 0; i < nbr_Accounts; ++i)
{
std::ostringstream oss;
oss << std::setw(10) << std::setfill('0') << i;
std::string filename = oss.str() + std::string(".txt");
std::cout << "I try to open this file : " << filename << std::endl;
std::ifstream f(filename.c_str());
// Work with your file
}
如果您想实现一个函数,测试有多少连续的文件命名0000000001.txt0000000002.txt0000000003.txt。。。存在,你可以这样做:
#include <fstream>
#include <iomanip>
#include <sstream>
//...
unsigned long int num_accounts()
{
unsigned long int num_acc = 0;
bool found;
do
{
std::ostringstream oss;
oss << std::setw(10) << std::setfill('0') << i;
std::string filename(oss.str() + std::string(".txt"));
std::ifstream f(filename.c_str());
found = f.is_open();
if(found)
++num_acc;
} while(found);
return num_acc;
}
以下是我在Chaduchon的帮助下使用的内容:
double num_of_accounts() {
unsigned long int number_of_accounts = 0;
unsigned long int count = 0;
ofstream ifile;
string filename = "00";
ostringstream oss;
bool found;
do {
ostringstream oss;
oss << setw(10) << setfill('0') << count;
string filename(oss.str() + string(".txt"));
ifstream f(filename.c_str());
found = f.is_open();
if (found){ ++number_of_accounts;}
count++;
} while (found);
return number_of_accounts;
}
相关文章:
- 生成随机长度的数字字符串
- 如何在c ++中将大数字字符串转换为整数?
- 将非数字字符串存储为二进制整数
- Flex 词法分析器规则,对包含连字符和斜杠的字母数字字符串具有积极的前瞻断言
- 如何在C++中将数字字符串拆分为数组
- 总结数字字符串输入的最佳方法
- 如何将输入的数字字符串转换为 int 数组
- 如何获得两个数字字符串的总和-C
- 使用 C++ 替换 txt 文件中的文本数字字符串
- 如何有效地将数字字符串值分配给整数
- String Stream in C++ 解析单词和数字字符串
- c++将大型数字字符串映射到数字字符串范围
- 获取用数字字符串表示的树中的所有直接父级/子级
- 如何从 char 数组中提取数字字符串成员
- 比较两个字母数字字符串
- 有没有一种方法可以设置浮点变量=某个数字*字符串中的变量
- 使用矢量对字母数字字符串进行排序
- 正在分析未知类型的数字字符串
- 如何在c++中从一个科学数字字符串中修剪后面的零
- 无法将字符串数组中的数字字符串转换为浮点值