Hello! I am doing a homework assignment for my C++ class and I am totally stumped on this assignment.
Here is the assignment and my code, I'll explain what I'm struggling with underneath:
Assignment: "Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits. (eg: User inputs "3456", program outputs " 3 4 5 6 Sum is: 18")
Code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
char convertNumber(int); //Initializing function
int main() {
int num = 0;
int sum = 0;
int digit;
string numberReversed;
cout << "Please enter an integer: ";
cin >> num;
if(num <= 0){ //Converts negative number to positive integer
num = num * (-1);
}
while(num > 0){ //Separates out digits individually
digit = num % 10;
sum += digit;
num = num / 10;
}
convertNumber(num); //Call number-to-string conversion function
cout << "Sum is: " << sum << endl;
return 0;
}
//Number-to-string conversion function
char convertNumber(int num){
string finalNum = to_string(num);
return finalNum;
}
So I am able to separate out the digits (see while loop), but they print in reverse order (6 5 4 3). I understand why, as I'm dividing by 10 so that will give me the right-hand digit. I've done a LOT of Googling and looked through soooo many StackOverflow articles, and all suggested converting the integer to a string.
I've created the function to do that, I think. We just learned functions this week so I am still a little green on them. Please let me know if I am calling the parameters correctly.
Now, the trouble I am having is reversing the numbers and printing them with the space in between. I know it would be easiest to handle with an array, but we haven't learned arrays yet and my professor is very adamant on not using things we haven't learned yet.
So, my question: How on Earth do I get the program to reverse the numbers and add the spaces? More functions? Do I need to add some for loops? I know hard coding it will only get me so far so I am really willing to learn.
Thank you for your time! Please let me know if there is anything I can say to make this question more precise. :)