Here's another problem I have been working on. This is purely for educational purposes, and I understand that it is probably not the most efficient way to execute this objective.
The goal is to read a user's input in the console/terminal (are these synonymous?), and count the occurrence of the integer values 0, 1, 2, 3, and 4 using a switch-case construction.
As currently constructed, I'm storing the user input as a character value, and comparing each character to the integers in character form (e.g. '0', '1'...).
When I run my code, after entering an example such as 1235000, I get zero values for everything. However, if I initiate the input with a character, such as a000125, the program executes correctly.
What is going on here, and how should I resolve this?
#include <stdio.h>
using namespace std;
int main()
{
int zeros=0;
int ones=0;
int twos=0;
int threes=0;
int fours=0;
int others=0;
int num;
printf("please enter a positive integer\n ");
scanf_s("%d",&num);
while ((num = getchar()) != EOF)
{
switch (num)
{
case '0':
zeros++;
break;
case '1':
ones++;
break;
case '2':
twos++;
break;
case '3':
threes++;
break;
case '4':
fours++;
break;
default:
others++;
}
}
printf("the number of zeros is %d\n", zeros);
printf("the number of ones is %d\n", ones);
printf("the number of twos is %d\n", twos);
printf("the number of threes is %d\n", threes);
printf("the number of fours is %d\n", fours);
printf("other characters/numbers: %d\n", others);
return 0;
}
Related
in my code, i don't understand why zero doesn't print i did all possible solutions that I know but it doesn't print zero.
#include <iostream>
using namespace std;
int main(){
int digits;
int numberOne = 0;
int integer;
cout<<"Enter the number: ";
cin>>digits;
while (digits != 0) {
numberOne = (numberOne * 10) + (digits % 10);
digits /= 10;
}
for (integer = numberOne; integer > 0; integer = integer / 10){
switch (integer % 10) {
case 0:
cout<<"Zero\n";
break;
case 1:
cout<<"One\n";
break;
case 2:
cout<<"Two\n";
break;
case 3:
cout<<"Three\n";
break;
case 4:
cout<<"Four\n";
break;
case 5:
cout<<"Five\n";
break;
case 6:
cout<<"Six\n";
break;
case 7:
cout<<"Seven\n";
break;
case 8:
cout<<"Eight\n";
break;
case 9:
cout<<"Nine\n";
break;
}
}
return 0;
}
zero doesn't print how do I fix it?
Expected output is 900 (nine zero zero) but zero doesn't print in my case. help thanks.
Because in this line:
for (integer = numberOne; integer > 0; integer = integer / 10){
the loop continues only if integer>0. Therefore you never see "Zero".
Why doesn't it print zero? Look at your loop
for (integer = numberOne; integer > 0; integer = integer / 10){
If integer equals zero then the loop is never entered. You need to be a bit smarter in your loop. How about counting digits?
int num_digits = 0;
while (digits != 0) {
numberOne = (numberOne * 10) + (digits % 10);
digits /= 10;
++num_digits;
}
Now that you have the number of digits, you can use that in your second loop
for (integer = numberOne; num_digits > 0; integer = integer / 10, --num_digits) {
...
}
You still need to treat zero as a special case, because if the user enters 0 then num_digits will equal zero and you again won't print anything. I'll leave you to figure out how to fix that.
#include <iostream>
using namespace std;
int main(){
int digits;
int arrayLength = 10;
cout<<"Enter the number: ";
cin>>digits;
string reverse_number[arrayLength]; //array to store the string of numbers like "Zero"
int array_counter=0;
while (digits != 0) {
switch (digits % 10) {
case 0:
reverse_number[array_counter++] = "Zero";
break;
case 1:
reverse_number[array_counter++] = "One";
break;
case 2:
reverse_number[array_counter++] = "Two";
break;
case 3:
reverse_number[array_counter++] = "Three";
break;
case 4:
reverse_number[array_counter++] = "Four";
break;
case 5:
reverse_number[array_counter++] = "Five";
break;
case 6:
reverse_number[array_counter++] = "Six";
break;
case 7:
reverse_number[array_counter++] = "Seven";
break;
case 8:
reverse_number[array_counter++] = "Eight";
break;
case 9:
reverse_number[array_counter++] = "Nine";
break;
}
digits /=10;
}
int num_digits = array_counter;
for (int i = 0; i < num_digits; i++) {
cout << reverse_number[--array_counter] <<" ";
}
return 0;
}
The reason why your zeros are not showing while doing for 900 is because when you are reversing 900 to 009, there is no condition mentioned to handle the leading zeros in 009 which are just ignored. For this the best approach would be to store them somewhere else like in a string or an array. You can also just store the number words directly to an array while you are converting, that way you wont lose the leading zeros.
The other answers have already addressed the main problem with your code.This answer focus on the post's title: how to print multiple numbers to words?
First, I would consider using an array of strings instead of a switch.
In order to retrieve a string for a given digit, you would just index that array.(see digits[c - '0'] below)
Also, if you are allowed to convert a number to a string, the code would reduce to walking that string and converting each character to a word.You could read the number directly as a string from the standard input, or use std::to_string on an integer.
Notice also that, when reading a character c from the a string of digits, c - '0' gives you an integer betweeen 0 and 9, which you can use as the array index.
Demo
#include <array>
#include <iostream>
#include <string> // to_string
std::array<std::string, 10> digits{
"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"
};
void digits_to_words(int n) {
for (unsigned char c : std::to_string(n)) {
std::cout << digits[c - '0'] << "\n";
}
}
int main() {
for (int n : { 0, 5, 105, 900 }) {
std::cout << "Number: " << n << "\n";
digits_to_words(n);
std::cout << "\n";
}
}
i am making a simple program that displays the behaviour of the person from the sentences that i write in switch statement cases. I want to randomly generate a number between 1 and 10 and use it in "switch(this place)". So far, i have written the following code and stuck here..
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int rand_range(int low, int high)
{
return rand()%(high-low) + low;
}
int main()
{
srand(time(NULL));
cout<<"Hi!, this program tells you about your behaviour"<<endl;
cout<<"press enter to continue";
cin.get();
switch( )
{
case 1:
{
cout<<"you are rude !";
}
case 2:
{
cout<<"you are smart";
}
case 3:
{
cout<<"you try to prove yourself special all the time";
}
case 4:
{
cout<<"you are good in sarcasm";
}
case 5:
{
cout<<"you look dumb, but deep inside you are intelligent";
}
case 6:
{
cout<<"you are always ready for a debate with someone";
}
case 7:
{
cout<<"you are very lazy";
}
case 8:
{
cout<<"you are dumber than what you look";
}
case 9:
{
cout<<"you always try to help others";
}
case 10:
{
cout<<"you have good decision making capabilities";
}
default:
{
cout<<"something wrong";
}
}
}
In your switch statement in the parentheses you want (rand() % 10) + 1. After you have seeded the random number generator the rand() function will return a number between 0 and RAND_MAX. RAND_MAX is a large number.
To get a random number in a range a standard trick is to use the % operator. rand() % 10 returns a number between 0 and 9 inclusive. Add 1 to get your range of 1 through 10.
I'm working in a program that converts from Roman to Decimal. I have to validate 2 things: One that the characters entered are M or D or C or L or X or V or I, in other words valid for processing.
Number two, I have to make sure that bigger characters value go first and if not to print and error message and have the user to try again (this is the part where I am stuck)
For instance, If I wanted to input 9 and I input IX it should display an error message because is not in Additive form. It should be VIIII. How can I code this so it compares characters to know whether bigger letter values are first and so on?
I keep getting incorrect validation.
Is there a way to assign a value to the letters in the string? I'm thinking in comparing them as int values which I know how to and from there validate input format.
void RomanNum::setRomanNumber() //get input and calculate decimal equivalent
{
//I 1, V 5, X 10, L 50, C 100, D 500, M 1000
int value = 0;
string input;
char current, next;
enum validationData { M, D, C, L, X, V, I };
bool validationCharacters = true;
//bool validationAdditiveForm = true;
getline(cin, input, '\n');
for (int i = 0; i < input.length(); i++) //calculate each Roman letter at a time
{
current = input[i];
next = current + 1;
if (current >= validationData(next))
{
switch (input[i])
{
case 'M':
value += 1000;
break;
case 'D':
value += 500;
break;
case 'C':
value += 100;
break;
case 'L':
value += 50;
break;
case 'X':
value += 10;
break;
case 'V':
value += 5;
break;
case 'I':
value += 1;
break;
default:
validationCharacters = false;
break;
}
}
else
{
cout << "\nInvalid order. Bigger values go first\n";
}
}
}
I would recommend a std::map<char, int> to hold the mapping between letetrs and values.
With the map, you can then convert the input string (a sequence of characters) to a sequence of values (std::vector<int>). From there on, it's just a single check to see if the vector is sorted, and a single function call to add up all values. (I'll leave finding the right function as homework)
So i need to have my switch statement go through and write out five two if the user says 52 but i cannot get it pass my 0-9. if they type 0-9 it works perfect but if i try to do any number past that it makes a blank. help!
#include <stdio.h>
int main (void)
{
int x;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
for(x;x<0;x++);
switch (x)
{
case 0:
printf("zero");
break;
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
case 5:
printf("five");
break;
case 6:
printf("six");
break;
case 7:
printf("seven");
break;
case 8:
printf("eight");
break;
case 9:
printf("nine");
break;
}
printf("\n\n");
return 0;
}
do {
switch (x%10) {
...
}
x = x / 10;
} while (x>0) ;
or to get it in the right order use recursion
void f(int x) {
if (x==0) return;
f(x/10);
switch(x%10) { ... }
}
This question has been asked-and-answered before.
The for-loop you wrote is empty, because the body of the loop ends with the semi-colon:
for(x;x<0;x++) /* Empty Body!!*/ ;
The way a typical for loop works is:
for( /*Initialize*/; /*Test*/; /*Change*/)
{
/* Body */
}
In your case, I think you want:
for(int i=0; i < x; ++i)
{
switch(x)
{
[...]
}
}
This will:
Initialize i to 0
Test if i is LESS THAN x (the number you entered)
Keep increasing i by 1, until it gets up to x.
I'm not going to do your homework for you but consider the following pseudo-code:
print_text_digits(x)
{
if (x >= 10) print_text_digits(x / 10);
switch (x) {
print "zero" through "nine" as appropriate
}
}
main()
{
scan number into x;
print_text_digits(x);
}
This relies on a recursive routine so that you get your digits processed one at a time, with the might significant digit printed first.
You could solve this with recursion.
void printDigit(int x) {
int digit = x%10;
if(digit!=x)
printDigit(x/10);
switch(digit) {
...
}
}
This will print the most significant figure first, unlike the while loops most people are mentioning.
I believe you need this:
#include <stdio.h>
int main (void)
{
int count = 0;
int x, count2;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
int aux = x;
while(aux>0) {
aux=aux/10;
count++;
}
count2 = count;
while(count) {
aux = x;
for(int i=count-1;i>0;i--)
aux=aux/10;
for(int i=count2-count;i>0;i--)
aux%=10;
switch (aux) {
case 0:
printf("zero");
break;
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;
case 5:
printf("five");
break;
case 6:
printf("six");
break;
case 7:
printf("seven");
break;
case 8:
printf("eight");
break;
case 9:
printf("nine");
break;
}
count--;
if(count) printf(" ");
}
printf("\n\n");
return 0;
}
Now, with an input 52 it will propelly return five two.
#include <stdio.h>
static const char * const num[] = {
"zero ", "one ", "two " , "three ", "four ",
"five ", "six ", "seven ", "eight ", "nine "
};
void printNum(int x)
{
if (x < 10) {
printf(num[x]);
return;
}
printNum(x / 10);
printNum(x % 10);
}
int main (void)
{
int x;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\nYou have entered:\n\n");
printNum(x);
return 0;
}
Here's what you need to do. Similar to what #simonc said, it's a good idea to convert the user input to a string, then loop through the characters. For each character, convert it into an int and then take that into the switch statement.
EDIT---------------------------
Here's a way with strictly using integers.
First find how many digits your integer has. You can do this by a method mentioned here.
Then do integer division starting from the largest power of 10 that divides the integer you have and divide the divisor by 10 until you reach 1. For example:
If user input is 213, it has 3 digits. We divide this by 100 first.
213/100 = 2
We take the 2 and put it into the switch statement, outputting 2. Now we're done with the hundreds digit, so now we take the 13 from 213 and divide it by 10.
13/10 = 1 So now we output one.
Keep doing this process until you get to the ones digit.
Does this make sense?
I've been trying to get this code working, but somehow I can't do it..
#include <iostream.h>
#include <stdio.h>
int main() {
int a,b,c;
int y=3;
int i=2;
int g[] = {20};
int m,k;
int Z;
printf("Enter a number for a");
scanf("%d", &a);
printf("Enter a number for b");
scanf("%d", &b);
printf("Enter a number for c");
scanf("%d", &c);
m=y;
do
{
Z = a+b-c;
switch(Z)
{
case '0':
case '1':
k=17;
m+=b;
break;
case '2':
m+=b;
m=a;
break;
case '3':
m=a-c;
m+=b;
m=a;
break;
case '7':
m+=b;
break;
default:
m=a;
break;
}
g[m] = m%i;
m--;
}while(m>b);
}
This is the scheme that I had to turn into coding. http://ff.tu-sofia.bg/PIK/Izpiti/MidTest07.html
y and i are 3 and 2 by default, the array g should contain 20 integers, and the users have to type values for a, b and c.
Z is an integer and your cases are looking for strings. get rid of the quotes around the numbers in the cases.
The array g does not contain 20 integers it contains one element 20 in this case. I think what you meant was g[20] = {}
Also How is Z calculated ? Is it (a+b)-c or a+(b-c)? You need parentheses to make your intent clearer
Z = a+b-c;
switch(Z)
{
case 0:
case 1:
k=17;
m+=b;
break;
case 2:
m+=b;
m=a;
break;