How to turn integers into string in c programming? (eg. 0 => zero)
Code Example:
https://onlinegdb.com/BygYM1L9V
#include <stdio.h>
#include <stdbool.h>
int main(int argc, const char * argv[]) {
int input, number, right_digit;
bool isNegative = false;
printf("Insert a number:\n ");
scanf("%d", &input);
// if keyed-in number is negative, make it positive, but remember it was negative
if ( input < 0 ) {
input = input;
isNegative = true;
}
if (isNegative == true){
printf("negative ");
}
number = 0;
// reversing the digits of input and store in number
while ( input ) {
// adds the last digit of input to value from right
number = 10 * number + input % 10;
input /= 10;
}
do {
right_digit = number % 10;
switch (right_digit) {
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;
}
number = number / 10;
} while (number != 0 );
printf("\n");
return 0;
}
Expected result for entering 1230 is one two three zero.
However, this code provides 123 and omits the 0. How do I turn integers into strings?
However, is there a better way of doing it? Is there any other method? C coders, please help
I'd drop the switch for a look-up table. Regarding numbers having to be parsed with % operator "backwards" from ls digit and up, simply store them digit by digit in a separate temporary array to easily re-order them.
void stringify (unsigned int n)
{
const char* LOOKUP_TABLE [10] =
{
"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine",
};
if(n == 0)
{
puts(LOOKUP_TABLE[0]);
return ;
}
int numbers[10]={0}; // assuming UINT_MAX = 4.29 billion = 10 digits
for(int i=0; i<10; i++)
{
numbers[10-i-1] = n%10;
n/=10;
}
bool remove_zeroes = true;
for(int i=0; i<10; i++)
{
if(!remove_zeroes || numbers[i]!=0)
{
remove_zeroes = false;
printf("%s ", LOOKUP_TABLE[numbers[i]]);
}
}
}
Out of your problem a typo in your code : input = input; must be input = -input;
It is easier to work on the number as a string, example :
#include <stdio.h>
int main() {
printf("Insert a number:\n ");
char s[32];
if (fscanf(stdin, "%31s", s) != 1) {
return -1;
}
char * p = s;
if (*p == '-') {
printf("negative ");
p += 1;
}
for (;;) {
switch (*p++) {
case 0:
case '\n':
if ((*s == '-') && (p == (s+2))) {
puts("missing number");
return -1;
}
putchar('\n');
return 0;
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;
default:
puts(" invalid number");
return -1;
}
}
}
Compilation and executions :
/tmp % gcc -pedantic -Wall -Wextra n.c
vxl15036 /tmp % ./a.out
Insert a number:
0
zero
vxl15036 /tmp % ./a.out
Insert a number:
-1
negative one
vxl15036 /tmp % ./a.out
Insert a number:
12305
one two three zero five
vxl15036 /tmp % ./a.out
Insert a number:
007
zero zero seven
vxl15036 /tmp % ./a.out
Insert a number:
-
negative missing number
vxl15036 /tmp % ./a.out
Insert a number:
a
invalid number
As you see the number is rewritten as it was enter, 0 at left are not removed and -0 is negative zero
It can be fun to write one thousand two hundred thirty four for 1234 ;-)
I made a small change to your program so that it loops through once before to get the number of digits, and then loops through count times for the switch statement.
#include <stdio.h>
#include <stdbool.h>
int main(int argc, const char * argv[]) {
int input, number, right_digit;
bool isNegative = false;
printf("Insert a number:\n ");
scanf("%d", &input);
// if keyed-in number is negative, make it positive, but remember it was negative
if ( input < 0 ) {
input = -input;
isNegative = true;
}
if (isNegative == true){
printf("negative ");
}
int count = 0;
int n = input;
//count the digits
while(n != 0)
{
n /= 10;
++count;
}
number = 0;
// reversing the digits of input and store in number
while ( input ) {
// adds the last digit of input to value from right
number = 10 * number + input % 10;
input /= 10;
}
for(int i = 0; i < count; i++) {
right_digit = number % 10;
switch (right_digit) {
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;
}
number = number / 10;
}
printf("\n");
return 0;
}
I think you use similar logic as this example integrated into your loop, but when you reverse the number the 0's get treated like leading 0's and are ignored. I didn't make any changes to the inside of the loop so that may need to be cleaned up.
test input:
12345000
output:
one two three four five zero zero zero
Related
From the book "Programming in C"
Write a program that takes an integer keyed in from the terminal and extracts and displays each digit of the integer in English. So, if the user types in 932, the program should display
nine three two
Remember to display “zero” if the user types in just a 0.
Its been hours and its still cant be solved.. Do anyone know how to? This is the code so far
#include <stdio.h>
int right_digit,number;
int main ()
{
scanf("%i",&number);
right_digit = number % 10;
switch (right_digit)
{
case '0':
printf("0");
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;
default:
break;
}
number = number / 10;
return 0;
}
The first problem here is, you're (wrongly) trying to use the character representation of the integer numbers. In your code, right_digit is supposed to represent an integer digit, not a character literal.
You must not to use the ''s, just write
case 0:
...
case 1:
and so on.
Just to add a bit on your mistake, it was considering the corresponding integer values of the character literal '0', '1' and so on. For ASCII, they are equivalent to
case 48:
case 49:
.
.
which is not what you intended.
That said,
You need to put the modulo calculation and switch-case inside a loop and carry out the conversion for all the digits of the input integer.
You need to start printing from the beginning (MSB), currently , you're printing from LSB. (Hint: Start printing the result of the modulo operation)
printf("0"); should be printf("Zero ");, as per the requirement.
/*USING SWITCH CASE ...ALSO YOU CAN USE '0' and negative numbers */
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int rem,num,sum=0,rem1,num1,add;
printf("enter the number:\n");
scanf("%i",&num);
if(num<0)
{
printf("minus ");
num=-num;
}
if(num==0)
{
printf("zero");
}
while(num!=0)
{
rem=num%10;
num=num/10;
sum=sum*10 +rem;
}
/*printf("%i\n",sum);*/
while(sum!=0)
{
rem1=sum%10;
sum=sum/10;
switch(rem1)
{
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;
default:
printf("invalid no");
}
}
return 0;
}
Hope this program will help you to understand the logic and I am also posting the solution for same problem using switch case....
/* Write a program that takes an integer keyed in from
* the terminal and extracts and displays each digit of the
* integer in English. So, if the user types in 932, the
* program should display >>> nine three two <<<.
* (Remember to display “zero” if the user types in
* just a 0.)
*/
/*USING IF-ELSE IF*/
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int rem,num,sum=0,rem1;
printf("enter the number:\n");
scanf("%i",&num);
if(num<0)
{
printf("minus ");
num=-num;
}
if(num==0)
{
printf("zero");
}
while(num!=0)
{
rem=num%10;
num=num/10;
sum=sum*10 +rem;
}
/*printf("%i\n",sum);*/
while(sum!=0)
{
rem1=sum%10;
sum=sum/10;
if(rem1==0)
{
printf("zero ");
}
else if(rem1==1)
{
printf("one ");
}
else if(rem1==2)
{
printf("two ");
}
else if(rem1==3)
{
printf("three ");
}
else if(rem1==4)
{
printf("four ");
}
else if(rem1==5)
{
printf("five ");
}
else if(rem1==6)
{
printf("six ");
}
else if(rem1==7)
{
printf("seven ");
}
else if(rem1==8)
{
printf("eight ");
}
else if(rem1==9)
{
printf("nine ");
}
else
{
printf("invalid no");
}
}
return 0;
}
I need to print the digit from the first to the last without use arrays, binary operations or recursion. In addition every digit should be print as a text.
#include <stdio.h>
int main () {
int a,x;
printf("Give a number : ");
scanf("%i", &a);
do {
switch ( x % 10 ) {
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;
default:
printf("Error \n");
break;
}
x /= 10;
} while ( a );
printf("\n");
}
The output for 123 is three two one. The desirable: one two three.
Any ideas?
Reverse the number before passing it to the Switch statement. See if the following program works. i haven't tested it yet.
#include <stdio.h>
int main () {
int a, temp, reverse = 0;
printf("Give a number : ");
scanf("%i", &a);
temp = a;
while (temp != 0)
{
reverse = reverse * 10;
reverse = reverse + temp%10;
temp = temp/10;
}
do {
switch ( reverse % 10 ) {
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;
default:
printf("Error \n");
break;
}
reverse /= 10;
} while ( reverse );
printf("\n");
}
You can count the digits in number and then use the / instead %.
For example, for 123 there are 3 digits, so you calculate pow (10,3-1) that is equal to 100. Then, 123/100 is equal to one. After that new number get 123%100 and next time you divide by 100/10. So 23/10 is equal to 2. Until you reach the less than 10 number and print that at the end. So 3 printed finally.
I have an assignment were I have to write a program that takes an integer keyed in from the terminal and extracts and displays each digit of the integer in English. I'm not able to use arrays or recursion, we're just starting with programming.
For example:
"123" returns "one two three"
My program is working well (for the most part), but the problem is that when you enter something like "0123" in the terminal the program returns "eight three"... WTH??
This is my code:
// Program that takes an integer and displays each digit in English
#include <stdio.h>
int main (void)
{
int num, digit;
int reversed = 0, backupZero = 0;
printf("Please enter an integer:\n");
scanf("%i", &num);
if (num == 0) // In case the input is just "0"
{
printf("zero");
}
while (num > 0) // Loop to reverse the integer
{
digit = num % 10;
reversed = (reversed * 10) + digit;
if ((reversed == 0) && (digit == 0)) // If the integer finishes in zero
{
++backupZero; // Use this to add extra zeroes later
}
num /= 10;
}
while (reversed > 0)
{
digit = reversed % 10;
reversed /= 10;
switch (digit)
{
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;
default:
printf("zero ");
break;
}
}
for (int counter = 0; counter < backupZero; ++counter) // Prints the extra zeroes at the end
{
printf("zero ");
--backupZero;
}
printf("\n");
return 0;
}
Probably is something on the mathematics, I admit I'm not good at it.
When you read in the number with
scanf("%i", &num);
You are letting scanf infer the base of the number. Numbers starting with 0 followed by other digits are interpreted as octal. So 0123 is not the same as 123. It is in fact, 83.
0100 = 64
020 = 16
03 = 3
---------
0123 = 83
To read the number as base 10, use
scanf("%d", &num);
If you want to handle numbers that start with '0', then I suggest that you read the user input as a string (array of characters) rather than as an integer.
In addition to that, instead of "doing a switch" on each character, you can use a simple array in order to map the correct word to each digit.
Here is one way for implementing it:
#include <stdio.h>
#define MAX_INPUT_LEN 100
const char* digits[] = {"zero","one","two" ,"three","four",
"five","six","seven","eight","nine"};
int main()
{
int i;
char format[10];
char str[MAX_INPUT_LEN+1];
sprintf(format,"%c%us",'%',MAX_INPUT_LEN); // now format = "%100s"
scanf(format,str); // will write into str at most 100 characters
for (i=0; str[i]!=0; i++)
{
if ('0' <= str[i] && str[i] <= '9')
printf("%s ",digits[str[i]-'0']);
else
printf("invalid character ");
}
return 0;
}
Oh, wow. It took me 3 or 4 hours to write following code. I'm into c only first week, so please be considerate.
Update: added working minus + some comments.
#include <stdio.h>
#include <math.h>
int main(void)
{
int num, count, user, out;
count = 0;
printf("Type in any int: ");
scanf("%d", &num);
// adding minus to the beginning if int is negative
if (num < 0)
{
num = -num;
printf("minus ");
}
user = num;
// creating a power to the future number
while (num != 0)
{
num = num / 10;
count++;
}
int i2;
i2 = count;
// main calculations: dividing by (10 to the power of counter) and subtracting from the initial number
for (int i = 0; i < i2; i++)
{
out = user / pow(10, count - 1);
user = user - out * pow(10, count - 1);
count--;
switch (out)
{
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;
case 0:
printf("zero ");
break;
default:
break;
}
}
printf("\n");
return 0;
}
There are some mistakes:
if ((reversed == 0) && (digit == 0)) (incorrect)
if ((reversed == 0) || (digit == 0)) (correct)
And in the last loop you should remove
--backupZero;
And code will read numbers better
So I've been working my way through Kochan's Programming in C and I've hit a snag on one of the questions which reads as follows:
"Write a program that takes an integer keyed in from the terminal and extracts and displays each digit of the integer in English. So if the user types in 932, the program should display the following: nine three two (Remember to display zero if the user types in just 0.)"
I had managed to get the program to print out the digits as words but unfortunately in reverse order. From there I thought it might be a good idea to reverse the number so to speak, but now when I run that value through my program only prints out "one one one ...." for how ever many digits long the number I enter in.
In other words, originally I managed to display 932 as "two three nine", but when I tried to reverse the number and run 239 through my program I only get "one one one".
If any one has any hints that could point me in the right direction it would be very much appreciated! My code is below:
#include <stdio.h>
int digitCount (int);
int reverseNumber (int);
int main(void)
{
//Chapter 6 Problem 6
int x, numberValue;
printf("Enter the number you'd like converted to words\n");
scanf("%i", &x);
numberValue = reverseNumber(x);
printf("The reverse is %i\n", numberValue);
do {
numberValue = numberValue % 10;
switch (numberValue) {
case 0:
printf("zero\t");
break;
case 1:
printf("one\t");
break;
case 2:
printf("two\t");
break;
case 3:
printf("three\t");
break;
case 4:
printf("four\t");
break;
case 5:
printf("five\t");
break;
case 6:
printf("six\t");
break;
case 7:
printf("seven\t");
break;
case 8:
printf("eight\t");
break;
case 9:
printf("nine\t");
break;
default:
break;
}
x = x / 10;
} while (x != 0);
return 0;
}
int digitCount (int u)
{
int cnt = 0;
do {
u = u / 10;
cnt++;
} while (u != 0);
return cnt;
}
int reverseNumber (int y)
{
int cnt, Rev;
cnt = digitCount(y); //returns number of digits
while (cnt != 0) {
Rev = Rev * 10 + y % 10;
y = y / 10;
cnt--;
}
return Rev;
}
In your reverseNumber function you have not initialized Rev. Make Rev=0
int reverseNumber (int y)
{
int cnt, Rev=0;
cnt = digitCount(y); //returns number of digits
printf("Digit count %d\n", cnt);
while (cnt != 0) {
Rev = Rev * 10 + y % 10;
y = y / 10;
cnt--;
}
return Rev;
}
In main in the do while loop use a temporary variable since you are overwriting numberValue with numberValue % 10. But the most ironic part in your program (where you complicated everything for yourself) is that there is no need to reverse the number at all. See the code here
In the way user entered - http://ideone.com/pORaP2
In reverse order - http://ideone.com/5GS8al
When you find modulo you get the number in the reverse order itself. Suppose you entered 234
First step 234%10 gives 4 prints four. And then makes 234 to 23
Second step 23%10 gives 3 prints three. And then makes 23 to 2
and then finally prints two.
Consider what the primary problem is you are dealing with, you need to process the left most digit first, then the next to the right, then the next. But the math of using modulus and division goes from right to left. So what you need is some way to either save the math processing and reverse, or have the output be delayed. Two options are available.
For an iterative approach you could utilize a FIFO queue type approach that holds the results of each digit and then prints out the queue. Could be as simple as an array with indexing:
int main(void) {
int x, i;
int result[32]; //arbitrary size
int index = 0;
printf("Enter the number you'd like converted to words\n");
scanf("%i", &x);
do {
results[index++] = x % 10;
x = x / 10;
} while( index < 32 && x != 0 );
//now print in reverse order
for(i = index-1; i >= 0; i--) {
switch (results[i]) {
case 0:
printf("zero\t");
break;
case 1:
printf("one\t");
break;
case 2:
printf("two\t");
break;
case 3:
printf("three\t");
break;
case 4:
printf("four\t");
break;
case 5:
printf("five\t");
break;
case 6:
printf("six\t");
break;
case 7:
printf("seven\t");
break;
case 8:
printf("eight\t");
break;
case 9:
printf("nine\t");
break;
default:
break;
}
}
}
There is second approach that works which is recursive. Here you delay the printing of the output until you reach the left most digit. The built in stack is used for by the recursive calls.
void printNumbers(int x);
int main(void) {
int x;
printf("Enter the number you'd like converted to words\n");
scanf("%i", &x);
printNumbers(x);
}
void printNumbers(int v) {
if( v > 9 ) {
printNumbers( v / 10 );
}
switch (v%10) {
case 0:
printf("zero\t");
break;
case 1:
printf("one\t");
break;
case 2:
printf("two\t");
break;
case 3:
printf("three\t");
break;
case 4:
printf("four\t");
break;
case 5:
printf("five\t");
break;
case 6:
printf("six\t");
break;
case 7:
printf("seven\t");
break;
case 8:
printf("eight\t");
break;
case 9:
printf("nine\t");
break;
default:
break;
}
}
Both approaches will solve the problem, but not if the input is a negative number.
My simple answer:
void printNum(int x)
{
static const char * const num[] = {
"zero ", "one ", "two " , "three ", "four ",
"five ", "six ", "seven ", "eight ", "nine "
};
if (x < 10) {
printf(num[x]);
return;
}
printNum(x / 10);
printNum(x % 10);
}
How can I remove an element from a vector in C without changing my print_vector function?
1) Here's the code that I made for removing an element on a position given from the keybord:
void remove_a_cost(int a)
{
int nr, c;
printf("Give the number of cost for remove: ");
scanf("%d", &nr);
if(nr>a)
{
printf("The remove is impossible!\n");
}
else
{
for(c=nr;c<=a;c++)
{
chelt[c]=chelt[c+1];
}
}
}
2)This is the print function
void print_costs(int a)
{
int i;
if(a>0 && a<=n)
{
for(i=1;i<=a;i++)
{
printf("\nCost %d\n\n",i);
printf("Day: %s\n", chelt[i].day);
printf("Sum: %d\n", chelt[i].sum);
printf("Type: %s\n", chelt[i].type);
}
}
}
3) Here's the add_new_cost() function
int add_new_cost()
{
int a,i;
printf("Nr of costs = ");
scanf("%d", &a);
if(a>0 && a<=n)
{
for(i=1;i<=a;i++)
{
printf("\nType the attributes for cost %d",i);
printf("\nDay = ");
scanf("%s",chelt[i].day);
printf("Sum = ");
scanf("%d", &chelt[i].sum);
printf("Type = ");
scanf("%s",chelt[i].type);
}
}
return a;
}
4) This is the main function
int main()
{
setbuf(stdout,NULL);
int b,choice;
do
{
printf("\nMenu\n\n");
printf("1 - Add a cost\n");
printf("2 - Print a cost\n");
printf("3 - Update a cost\n");
printf("4 - Delete a cost\n");
printf("5 - Exit\n\n");
printf("Command = ");
scanf("%d",&choice);
switch (choice)
{
case 1: b=add_new_cost();
break;
case 2: print_costs(b);
break;
case 3: update_cost(b);
break;
case 4: remove_a_cost(b);
break;
case 0: printf("Goodbye\n");
break;
default: printf("Wrong Choice. Enter again\n");
break;
}
} while (choice != 0);
return 0;
}
Example:
If I have 4 elements on the vector:
1)Type the attributes for cost
Day = luni
Sum = 2
Type = dsasa
Type the attributes for cost 2
Day = marti
Sum = 23
Type = adsds
Type the attributes for cost 3
Day = miercuri
Sum = 23
Type = asd
Type the attributes for cost 4
Day = joi
Sum = 232
Type = asdas
and I try to delete, let's say the 3rd element, this is what I receive when I print:
Cost 1
Day: luni
Sum: 20
Type: maradf
Cost 2
Day: marti
Sum: 23
Type: afas
Cost 3
Day: joi
Sum: 45
Type: sdfadsf
Cost 4
Day:
Sum: 0
Type:
The element(COST 4) appears when it should've been deleted. Is there a solution for deleting the element WITHOUT changing the print function?
After updating of question, everything is clear, do these modifications:
int remove_a_cost(int a)
{
int nr, c;
printf("Give the number of cost for remove: ");
scanf("%d", &nr);
if (nr > a)
{
printf("The remove is impossible!\n");
}
else
{
for (c = nr; c <= a; c++)
{
chelt[c] = chelt[c + 1];
}
a--; // decrease a
}
return a; // return new size
}
And
switch (choice)
{
case 1: b = add_new_cost();
break;
case 2: print_costs(b);
break;
case 3: update_cost(b);
break;
case 4: b = remove_a_cost(b); // <- store returned value in b
break;
case 0: printf("Goodbye\n");
break;
default: printf("Wrong Choice. Enter again\n");
break;
}
Your code is a bit messy. You should try to give meaningful names to your variables.
But, for what I understand, the print_costs function receives the value of the last 'cost' that it should print.
Perhaps you're passing it the wrong value after you remove a 'cost'.