-
array output
The code below compiles and runs but it doesn't do what I want it to do. I want it to print each element of the array with 3 spaces in between. Instead, it is printing all five elements received from the keyboard and three spaces. What do I need to change or add??
//input 5 digit number and print each number separated by 3 spaces
#include <iostream.h>
#include <iomanip.h>
int main()
{
const int SIZE = 4;
int number[SIZE];
cout << "Please enter a 5 digit number: ";
for(int i=0;i<SIZE;i++)
{cin >> number[i];
cout << number[i] << " ";}
return 0;
}
-
use the modulus command (%)
12345
for the one use 12345%10000 this command will get you the one and then you may want to store the remainder. then keep doing this for the next number down.
store=12345/10000 (gets you 2345);
store/=1000; (gets 345)
keep doing that and you should be able to get it to output what you want.
-
also if your just using one five digit number you would not need to use an array.
-
got to be a better way
I am trying to find a better way to do this. I wrote the below code, but it is not working. How can I get this to work? I created an array to hold the values entered from the keyboard. I then created a pointer to the array attempting to store the address of each element from the array in the pointer variable and then print out the value of each element separated by " ".
//input 5 digit number and print each number separated by 3 spaces
#include <iostream.h>
#include <iomanip.h>
int main()
{
const int SIZE = 4;
int number[SIZE];
int *num[SIZE];
cout << "Please enter a 5 digit number: ";
cin >> num;
for(int i=0;i<SIZE;i++)
cin >> number[i];
num[] = &number[i];
//for(int i=0;i<SIZE;i++)
cout << num[0] << " ";
return 0;
}
-
store five digit number as string.
print out each digit separated by 3 spaces
char space = ' ' ;
char number[6];
cout << enter 5 digit number;
cin >> number
for(int i = 0; i < 5; i++)
cout << number[i] << space << space << space;
you could use ' ' wherever I used space in th output statement. You could declare an empty string consisting of three spaces and send it to cout after number[i]. You could use fixed length field with setw(4) between cout and number[i] if i > 0 and not use setw() if i = 0. You could store 5 digit nuimber as int and peel off one digit at a time with a repeating series of modulo by 10 followed by division by ten until the value of the number you are working with is less than 10 and then space each digit however you want. Lot's of choices here.