If I type a number, the computer should display the number by giving space between between them.
For example; if I type 56, the computer should print out 5 6. Similarly if I type 5681, the computer should print out 5 6 8 1. Also, if i type -2345, the computer should print out 2 3 4 5.
#include<iostream> //include iostream for input and output
#include <string> //include string for the string object
usingnamespace std; //using namespace std for string and cout
int main()
{
string userinput; //stores the numbe that the user enters
cout << "Please enter a number: ";
getline(cin, userinput); //Place the user's # that they typed into the string userinput
int numberlength = userinput.size(); //number length holds the # of digits of the user input
for (int i = 0; i < numberlength; i++) //for each digit in the user input
{
if (userinput[i] >= '0' && userinput[i] <= '9') //if digit is 0-9
{
cout << userinput[i] << " "; //Print out digit with a space after the digit
}
}
return 0;
}
I have rewritten it to use the knowledge that you know.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream> //include iostream for input and output
usingnamespace std; //using namespace std for string and cout
int main()
{
char userinput; //stores the digit
cin >> userinput; //get single character from user input
while (userinput != '\0') //while not at null terminator from user pressing enter
{
if (userinput >= '0' && userinput <= '9') //if entered character is a digit
{
cout << userinput << " "; //print character with a space
}
cin >> userinput; //get next character to check if it is null terminator or another digit
}
}
@Pindrought. We don't do peoples assignments here, which is exactly what you did. Next time, help him out with tips and such, and let him write his own code, this way he will learn nothing.
Without knowing the point of the exercise it's hard to suggest a particular solution.
If you've only been working with int variables and loops, etc, when there is another solution which works with int maths. As you haven't touched on arrays then it start off by working out the highest power of ten for the number (using a while loop.) Etc.
These kinds of homeworks aren't interested in your ability to play with strings, so forget all that.
The idea is for you to be able to separate an integer value into digits. Do that with basic math: division and remainder. C++ provides two simple operators that do just that.
I don't know if you are expected to use recursion for this, but without arrays of any kind you must either:
1) use recursion
2) reverse the digits of the number before displaying them
Neither method is particularly easy to understand at first.