Hello, I am starting programming and am on my second assignment.
The program is required to ask the user for an integer, then convert the integer into a string
Then the string should display each number (no duplicates) with it's position.
Like so:
7377683
3 : 0 5
6 : 2
7 : 3 4 6
8 : 1
7377683
Using the positions of each number (the last number has the position 0 ) the full number should be reconstructed as an integer.
Note: The integer should be cast as an unassigned long int.
I have the code to should the numbers with positions but i cannot get rid of the duplicates and enter their position next to the same numbers position. Also to reconstruct the integer at the end i would like some guidance as i am not sure.
I am new to C++ so you may need more information. Thank you in advance for your time.
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <algorithm>
usingnamespace std;
int main()
{
longunsignedint num;
int i;
cout<<"ENTER A 9 DIGIT NUMBER : " <<endl; //ask user to enter integer
cin>>num;
if (num > 999999999)
{
cout <<"ERROR: Enter a 9 digit number" <<endl;
cin.clear();
return 0;
}
string result;
stringstream out; //convert int to string
out << num;
result = out.str();
reverse(result.begin(), result.end()); //reverse the string
for (i= 0; i < result.length(); i++)
{
cout<< result.at(i) << " : " << i <<endl;
}
return 0;
}
I cannot seem to get this to work and have spend multiple hours changing the code to loop correctly but am really having no luck. If someone could please give it a glance i would be most appreciative.
for (i= 0; i < result.length(); i++)
{
cout<< result.at(i) << " : " << i <<endl;
}
This just outputs the digit at position i then outputs i. If you want to do it the way desired you would first have to find all the unique values then find all the positions of that unique value.
Yes, that is exactly the problem giblit, I understand how the program should go but having problem actually coding it in the program. I am not still new to coding but willing to learn :)
Thank you JLBorges for the response I will spend an hour or two understanding the code. I will mark this thread as solved when i have understood :D
I have understood the code and understand why my code was not working. I need to reconstruct the initial integer with the positions that have been listed. Would someone be able to give me a hint so that I know i am going the right ways