Increment number in string C++

19.5k views Asked by At

I'm trying to increment the name of the file based on the number associated with the filename. If I make the variable postFix an int type, it gives an error (understandably) since I can't concatenate an int to a string type.

In that case how do I increment string variable?

for (int i = 0; i <= 10; i++) 
{
  std::string postFix = "1"; // int postFix = 1 gives an error
  std::cout << (std::string("Image" + postFix + std::string(".png")));
}
7

There are 7 answers

0
Cory Kramer On BEST ANSWER

You can use std::to_string to create a std::string from your int value.

for (int i = 0; i <= 10; i++) 
{
    std::cout << "Image" + std::to_string(i+1) + ".png";
}

Although in this case you might as well just use the stream operator<<

for (int i = 0; i <= 10; i++) 
{
    std::cout << "Image" << i+1 << ".png";
}
2
Olivier Poulin On
int value = atoi(postFix.c_str());
value++;
postFix = std::to_string(value);
0
twentylemon On

use std::to_string

for (int i = 0; i <= 10; i++) 
{
    int postFix = 1;
    std::cout << (std::string("Image" + std::to_string(postFix) + std::string(".png")));
}
0
Scott Hunter On

You don't; you use an integer variable, and make a string representation of it to build the file name: std::to_string(n)

2
mazhar islam On

Increment the int 'Number' as your wish, then convert it into string and finally append it with the file name (or exactly where you want).

Headers needed:

#include <iomanip>
#include <locale>
#include <sstream>
#include <string> // this should be already included in <sstream>

And to convert the 'Number' to 'String' do the following:

int Number = 123;       // number to be converted to a string

string Result;          // string which will contain the result

ostringstream convert;   // stream used for the conversion

convert << Number;      // insert the textual representation of 'Number' in the characters in the stream

Result = convert.str(); // set 'Result' to the contents of the stream

          // 'Result' now is equal to "123" 

This operation can be shorten into a single line:

int Number = 123;
string String = static_cast<ostringstream*>( &(ostringstream() << Number) )->str();

Reference taken from here.

0
Vlad from Moscow On

Write simply

std::cout << std::string("Image" ) + std::to_string( i + 1 ) + ".png";

Or even like

std::cout << "Image" + std::to_string( i + 1 ) + ".png";

Or you can define at first a string

std:;string = "Image" + std::to_string( i + 1 ) + ".png";

and then output it

std::cout << s;

0
Michel Billaud On

It seems you're getting it more complicated than necessary.

for (int i = 1; i <= 10; i++) {
     std::cout << "Image" << i << ".png";
   }

or

for (int i = 1; i  <= 10; i++) {
    std::string filename = "Image" + std::to_string(i) + ".png";
    // do something with filename
}

to_string(int) appeared in C++11.