Hi,
I am trying to write a program that will read an integer as a string and it will add 1 to this integer. For example if it read 234, it will return 235.
My attempt is this:
#include <fstream>
#include <string>
using namespace std;
void addone(string& num){
int n=num.size();
int i=n-1;
while(num[i]=='9'){
if (i==0){
num[i]=1;
for (int j=1;j<=n;j++){
num[j]='0';
}
}
num[i]='0';
i--;
}
if (i>=0){
num[i]=num[i]+1;
}
}
int main()
{
ifstream in("something.in");
ofstream out("something.out");
string num;
in >> num;
addone(num);
out << num;
return 0;
}
This code works good generally.
The only problem is that if the number has only 9s it outputs only 0s without 1.
Can you help me to fix this problem?