I need to make a program where a user inputs a string of numbers.
It then outputs the numbers grouped so that each grouping, separated by a space, is larger than the last when you put the numbers together.
If the remaining digits together equal a sum smaller than the previous grouping they are omitted.
Ex.:
314159265 would output 3 14 15 92
Here: 3 < 14 <15 < 92 but 65 was omitted because it is less than 92
or
9876543210 would output 9 87 654 3210
Here: 9 < 87 < 654 < 3210
It has to do this 5 times with strings 1-20 characters long.
My code works for shorter strings, ie the ones above, but when they are longer than around 12 characters the end output messes up.
Ex.:
98765432101234567898 outputs 9 87 654 3211 12333 instead of 9 81 654 3210 12345 67898
Here: 9 < 87 < 654 < 3211 < 12333 it should output 9 < 87 < 654 < 3210 < 12345 < 67898
I have no idea why it doesn't work with larger strings and any help would be greatly appreciated.
#include<iostream>
#include<iomanip>
#include<math.h>
#include<string>
#include<stdlib.h>
using namespace std;
void input (string &a,string num[20]){
string numfinal,temp;
cout<<"Enter the string of numbers: ";
getline(cin, a);
int length=a.length();
for(int i=0;i<length;i++){
num[i]=a.substr(i,1);
}
for(int r=0;r<length;r++){
int n=atoi(temp.c_str());
int o=atoi(num[r].c_str());
int p=temp.length();
if((length-r<=p)&&(o<n)){
}
else if((o>n)||(r==0)){
temp=num[r];
numfinal=numfinal+temp+" ";
}
else if((o<n)||(o=n)){
int w=n;
temp=num[r]+num[r+1];
n=atoi(temp.c_str());
if(n<w){
int a=1;
int q=r+2;
while(n<w){
temp=temp+num[q];
n=atoi(temp.c_str());
p++;
a++;
}
numfinal=numfinal+temp+" ";
r=r+a;
}
else{
numfinal=numfinal+temp+" ";
r++;
}
}
}
cout<<numfinal<<endl;
}
int main(){
string a;
string num[20];
for(int r=0;r<5;r++){
input(a,num);
}
return 0;
}
314159265, could produce the output:31 41 59 265? It seems like there could be many outputs for a single input. And if so, how would you choose which is the 'correct' output?atoihas a number of failure cases you are not checking.stoiorstrtolmay be better choices.3141592653589793238no zeroes and it still screwed up the end, outputting3 14 15 92 653 5899 9322. I also triedstoiand it gives the "Not declared in this scope" error code