【问题标题】:How can I increment a number in a string form in C++?如何在 C++ 中以字符串形式递增数字?
【发布时间】:2014-12-29 02:22:46
【问题描述】:

好的,我正在学习 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 控制台上。

谢谢

【问题讨论】:

  • 为什么不只统计目录中的文件?
  • 我也没学过。
  • 将“c++ 读取目录”打入你喜欢的搜索引擎。
  • 我会调查,但我想确保它计算特定文件。以防万一我放了一个示例文本文件或另一个文件。谢谢你的建议。
  • 对,就这样吧。阅读方向并决定,对于每个文件,是否计算它。

标签: c++ string double increment fstream


【解决方案1】:

您应该使用流来做到这一点。看这个例子:

#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.txt 0000000002.txt 0000000003.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;
}

【讨论】:

  • 感谢您的帮助。
【解决方案2】:

这是我在 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多