kingcobra1986
kingcobra1986

Reputation: 971

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

Ok so I am learning C++. I want check to see how many files exist for a bank account program for class. My method of doing this is to run a loop to run through and attempt to open "0000000001.txt" to see if it is valid, then "0000000002.txt", and so on. The difficult part is the numbers have the leading zeros( it needs to be a total of 10 digits before ".txt".

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;
}

Or possibly a way to format the double to be 10 digits long and then convert to string using to_string()? I tried googling it but I don't know if I am using the wrong keywords.

This is on win console if that helps.

Thank you

Upvotes: 2

Views: 2928

Answers (2)

Caduchon
Caduchon

Reputation: 5201

You should use streams to do that. See this example :

#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
}

If you want to implement a function testing how many consecutive files named 0000000001.txt 0000000002.txt 0000000003.txt ... exist, you can do it by this way :

#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;
}

Upvotes: 8

kingcobra1986
kingcobra1986

Reputation: 971

Here is what I used with the help of 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;
}

Upvotes: 0

Related Questions