You must implement a counter from the number written in the String. Those. at each iteration of the cycle, the string number should be increased by 1. That is, was "123", after the next iteration should be "124", etc.

I have a problem with discharges. Here I have such a piece of code increases only from 0 to 9, but I don’t know how to increase and add a new digit (tens, hundreds, etc.).

if(str[(str.size()-1]-'0'< 9) str[(str.size()-1]+=1; 
  • Isn't it easier to increase the number, and to write it in the string via sprintf ()? - Vladimir Martyanov
  • Can it be easier every time to convert it to an int, increase and write the result back? - avp Nov.
  • If the digit is equal to 9 - then you make it 0 and at the same time put some variable in 1. On the next cycle, when you process the highest digit add 1 + this variable to it. If the transfer does not occur - then the variable is reset to zero - Mike

2 answers 2

As I understand it, it is the person who wants to work with the string ... Then - here:

 void inc(string&s) { int l = s.length(); bool carry = true; for(int i = l-1; carry && i >= 0; --i) { if (carry) s[i]++; if (carry = (s[i] > '9')) s[i] = '0'; } if (carry) s = '1' + s; } int main(int argc, const char * argv[]) { string s = "193"; for(int i = 0; i < 20; ++i) { inc(s); cout << s << endl; } s = "993"; for(int i = 0; i < 20; ++i) { inc(s); cout << s << endl; } } 

    You can do this as follows, as shown in the demo program.

     #include <iostream> #include <string> int main() { std::string cnt( "999" ); std::cout << cnt << std::endl; cnt = std::to_string( std::stoul( cnt ) + 1 ); std::cout << cnt << std::endl; return 0; } 

    The output of the program to the console:

     999 1000 
    • But if cnt turns out to be more than 2 ^ 64, then nothing good will come of it. - Mikalai Ramanovich
    • @MikalaiRamanovich As one movie character in a film featuring Schwarzenegger, I love smart people, but I don't like smart people. Usually, counters assume the use of some integer objects for use as a counter. So if you are not satisfied with, say, the type usigned long, then you can use the type unsigned long long. But it all depends on the specific task. - Vlad from Moscow
    • @MikalaiRamanovich The perfect, perfect solution I proposed. If you have such counters that do not fit into any integer type, then you will have to choose another solution. But this does not mean at all that my decision is incorrect. - Vlad from Moscow