如何在C++中以字符串形式递增数字

How can I increment a number in a string form in C++?

本文关键字:数字 字符串 C++      更新时间:2023-10-16

好的,我正在学习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;
}