Not getting correct variable assignment from getchar in C - c

I'm writing a simple calculation program, however the only string handling functions I can use are getchar and putchar. Right now I'm just trying to assign the numbers from input to variables, but when I print the variable it's some random number. For example, I entered 3 into the console and the output was 505110. Any help would be appreciated. Thank you.
#include <stdio.h>
#include "math.h"
int addFunction( int, int);
int subtractFunction(int, int);
int multiplyFunction(int, int);
int modulusFunction(int, int);
float divideFunction(float, float);
int main(int argc, const char * argv[])
{
int iochar = 0;
char num1 = 0, num2 = 0, continuePrompt, operator = 0;
do {
iochar = getchar();
getchar();
if ((iochar >= 0) && (iochar <= 20000)) {
num1 = iochar;
}
if ((iochar == '+') || (iochar == '-') || (iochar == '*') || (iochar == '/') || ( iochar == '%')) {
operator = iochar;
}
if ((num1 >= 0) || ((iochar >= 0) && (iochar <= 20000))){
num2 = iochar;
}
switch (operator) {
case '+':
iochar = addFunction(num1, num2);
break;
case '-':
iochar = subtractFunction(num1, num2);
break;
case '*':
iochar = multiplyFunction(num1, num2);
break;
case '%':
iochar = modulusFunction(num1, num2);
break;
case '/':
iochar = divideFunction(num1, num2);
break;
}
putchar(iochar);
printf("Would you like to make another calulation? (y or n)");
scanf("%c", &continuePrompt);
} while (continuePrompt != 'n');
return 0;
}
int addFunction(int x, int y){
return x + y;
}
int subtractFunction(int x, int y){
return x - y;
}
int multiplyFunction(int x, int y){
return x * y;
}
int modulusFunction(int x, int y){
return x % y;
}
float divideFunction(float x, float y){
return x / y;
}

The code is working exactly correct. When you enter a "3" in ASCII that's really the hex value 0x33, you're printing the value in dec (%d) thus you'll see a 51 on the output.
Now you're failing to consume the newline character that was entered, so getchar() is skipping the input on the second pass and is assuming you passed in a '\n' ASCII, which is hex 0xa and thus 10 is printed next.
You don't print any newlines or spaces so on the output you'll see:
3 (I entered that)
5110 (the output from '3''\n')
To fix the main problem, consume the new line character:
int main(int argc, const char * argv[]) {
int iochar, num1, num2;
char continuePrompt = 0, operator;
do {
iochar = getchar(); // Get input from user
getchar(); //Consume new line character
When you're printing the values, you're going to get ASCII values back, so if you want the dec, you're good, if you want it in character:
printf("%c", num1);
if you wanted it in hex (0x??)
printf("%#x", num1);
Also I'd print a new line or spaces or something more helpful then just a string of output to help find problems like this.
Finally this condtion:
while (continuePrompt != 'no');
Is wrong. That can't happen, check against 'n', you can't have 'no' in a single character.

Use %c instead of %d
i.e.
printf("%c", num1);
Also,you should initialize the variables.
i.e
int iochar=0, num1=0, num2=0;
char continuePrompt = 0, operator=0;

Since you're only allowed to use putchar and getchar, I assume that you're not allowed to use printf in order to present the result. In order to use an actual number with putchar you'll have to take each digit and transform it to the correct ASCII value.
Fortunately this is very simple, since
digitRepresentationASCIIValue == singleDigitValue + '0';
However, this will only work on a single digit. So you'll have to get the length of a number and use putchar for each digit. This is very simple:
void putNumber(int num){
int order = 1; // even zero has at least one digit
int tmp = num; // even zero has at least one digit
while(tmp /= 10)
order *= 10; // count digits
if(num < 0)
putchar('-'); // sign
while(order > 0){
// put a single digit, see above how to calculate the ASCII value
putchar('0' + ( ( num / order ) % 10));
order /= 10;
}
}
In order to actually read values you would have to do the exact opposite: check whether the character provided by getchar is a digit, and modify your current number:
int num[2] = {0,0};
int currentNum = 0;
int iochar = getchar();
while(!isNewline(iochar) && iochar != EOF){
if(isDigit(iochar)){
num[currentNum] = num[currentNum] * 10 + iochar - '0';
}
else if(isOperator(iochar)){
if(currentNum == 1)
num[0] = operate(num[0],num[1],operator);
else
currentNum = 1;
operator = iochar;
num[1] = 0;
}
iochar = getchar();
}
isDigit, isNewline and isOperand are left for exercise, all three are very simple but they will give you a better idea of ASCII values. operate contains your switch statement.
Note that I used int num[2] = {0,0};. This enables (in addition to currentNum) to write something like
3 + 3 + 3 / 9
Note that all operators are evaluated from left to right, as such the result of the example above will be 1 and not 6.3333333.
Exercises:
Don't publish your solution here, but do them for yourself as they should help you to improve your ASCII/char skills. For some exercises an ASCII table might be helpful.
Explain why the digit representation is so simple. Hint: Where and in which order are numbers defined in ASCII? What happens if you increase the value of a char?
Implement the missing isDigit, isNewline and isOperand.
The code for the input isn't commented, especially this line is missing a comment:
num[currentNum] = num[currentNum] * 10 + iochar - '0';
What exactly happens there? If num[currentNum] is too complicated for you at the moment just use num1 and print the value before you read the second one. Hint: Have a look at exercise #1.
Even if the operators would be evaluated in the right order (multiplication before addition), the result wouldn't be 6.333333 but 6. Why is that? What would you have to change in your current program?

First, you need to cast the input from "getchar", since it is an ascii input.
iochar = atoi(getchar());
then you can compare it against an integer value.

To start with, return value of getchar is char, promoted to int. So, please use an char variable to store it.
Secondly, to convert the input char to int, use something like:
int num1 = iochar - '0';

Related

Evaluate a simple mathematical expression with limited tools, no arrays, and no library functions

Here's a question from the last year's first "Intro to programming" exam at my uni:
Using the getchar() function read an input sequence consisting of
numbers, + and - signs. The output should be the result of those
arithmetical operations.
For example, if the input is 10+13-12+25-5+100, the output should be 131.
Now, given that I have a little bit of C experience before attending uni, this problem seems easy to solve using pointers, arrays, etc.
But here's the catch: on the exam you can only use things that the students were taught so far. And given that this exam is only like a month after the start of the school year, your options are fairly limited.
You can only use variables, basic input/output stuff, operators (logical and bitwise), conditional statements and loops, functions.
That means no: arrays, strings, pointers, recursion, structures, or basically any other stuff that makes this easy.
How in the hell do I do this? Today is the second time I've spent 3 hours trying to solve this. I have solved it successfully, but only after "cheating" and using arrays, string functions (strtol), and pointers. It's important for me to know how to solve it by the rules, as I'll have similar stuff on the upcoming exam.
Edit: my attempts so far have amounted to using the while loop combined with getchar() for input, after which I just get stuck. I don't have the slightest idea of what I should do without using more "tools".
The solution is quite simple, but it might not be obvious for a beginner. I will not provide a complete program, but rather outline the steps needed to implement this with only a few variables.
First of all, it's important to notice two things:
Your input can only contain one of -, + or any digit (0123456789).
The getchar() function will read one character of input at a time, and will return EOF when the end of the input is reached or an error occurs.
Now, onto the solution:
Start by reading one character at a time, in a loop. You will only stop if you reach end of input or if an error occurs:
int c;
while ((c = getchar()) != EOF) {
// logic here
}
Start with an accumulator set to 0, and "add" digits to it every time you encounter a digit.
// outside the loop
int acc = 0;
// inside the loop
if (/* c is a digit */)
acc = acc * 10 + (c = '0');
Hint: that /* c is a digit */ condition might not be simple, you can put this in the else of the check for - and +.
Every time you encounter either - or +, remember the operation, and each time you encounter an operator, first perform the previous operation and reset the accumulator.
// outside the loop
int op = 0;
int result = 0;
// inside the loop
if (c == '+' || c == '-') {
if (op) {
// there already is a previous operation to complete, do it
if (op == '+')
result += acc;
else
result -= acc;
} else {
// first operation encountered, don't do anything yet
result = acc;
}
acc = 0; // reset
op = c; // remember the current operation for the future
}
When you reach the end of the input (i.e. you exit the loop), perform the last operation (same logic inside the if from point 3).
Output the result:
You would normally write something like:
printf("%d\n", result);
However, if you cannot use string literals ("%d\n") or the printf() function, you will have to do so manually using putchar(). This is basically the opposite of what we did before to scan numbers into an accumulator.
Print the sign first if needed, and make the value positive:
if (result < 0) {
putchar('-');
result = -result;
}
Find the maximum power of 10 that is lower than your number:
int div = 1;
while (result / div / 10)
div *= 10;
Use the power to extract and print each digit by division and modulo by 10:
while (div) {
putchar('0' + ((result / div) % 10));
div /= 10;
}
Note: the '0' + at the beginning is used to convert digits (from 0 to 10) to the relative ASCII character.
End with a newline:
putchar('\n');
When writing a parser, I typically find myself that I "buffer" the next operation that "will be done". When the input changes state - you are reading digits, but then you read an operation - then you execute the "buffered" action and buffer the next operation that will be done in the future.
Example:
10+13-12
^^ - we read 10
^ - result=10 - we buffer that we *will* have to do + in the future
^^ - reading 13
^ - och we stopped reading numbers!
we execute _buffered_ operation `+` , so we do result += 13
and buffer `-` to be done in the future
^^ - we read 12
^ - och, EOF! we execute buffered operation `-` , so we do result -= 12
- etc.
The code:
#include <stdio.h>
int main() {
int result = 0; // represents current result
int temp = 0; // the temporary number that we read into
int op = 0; // represents the _next_ operation that _will_ be done
while (1) {
int c = getchar();
switch (c) {
// we read an operation, so we should calculate _the previous_ operation
// or this is end of our string
case '+': case '-': case EOF:
if (op == 0) {
// we have nothing so far, so start with first number
result = temp;
} else if (op == '+') {
result += temp;
} else if (op == '-') {
result -= temp;
}
// the next operation we will do in future is stored in op
op = c;
// current number starts from 0
temp = 0;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
// read a digit - increment temporary number
temp *= 10;
temp += c - '0';
break;
}
// we quit here, the result for last operation is calculated above
if (c == EOF) {
break;
}
}
printf("%d\n", result);
// As I see it was mentioned that "%d\n" is a string,
// here's the simplest algorithm for printing digits in a number.
// Extract one digit from the greatest position and continue up
// to the last digit in a number.
// Take negative numbers and throw them out the window.
if (result < 0) {
putchar('-');
result = -result;
}
// Our program currently supports printing numbers up to 10000.
int divisor = 10000;
// 000100 should print as 100 - we need to remember we printed non-zero
int was_not_zero = 0;
while (divisor != 0) {
// extract one digit at position from divisor
int digit = result / divisor % 10;
// if the digit is not zero, or
// we already printed anything
if (digit != 0 || was_not_zero) {
// print the digit
putchar(digit + '0');
was_not_zero = 1;
}
// the next digit will be to the right
divisor /= 10;
}
putchar('\n');
}
#include <string.h>
#include <stdio.h>
void operate(int * sum, int * n, char todo) {
if (todo == 1) *sum += *n;
else if (todo == -1) *sum -= *n;
printf("%s %d\n", todo == 1 ? "ADD :" : "SUB :", *n);
*n = 0;
}
int main()
{
char * problem = "10+13-12+25-5+100";
int len = strlen(problem);
int i=0;
char c;
int n = 0;
int sum = 0;
char todo = 1;
while(i < len)
{
c = problem[i++];
if (c < 48 || c >= 58)
{
// Adds or subtracts previous and prepare next
operate(&sum, &n, todo);
if (c == '+') todo = 1;
else if (c == '-') todo = -1;
}
else
{
// Collects an integer
if (n) n *= 10;
n += c - 48;
}
}
operate(&sum, &n, todo); // Last pass
printf("SUM => %d\n", sum); // => 131
return 0;
}
#include <stdio.h>
void do_operation(char next_operation, int * result, int * number){
if (next_operation == '+'){
*result += *number;
*number = 0;
} else if (next_operation == '-'){
*result -= *number;
*number = 0;
} else {
printf("Unknown operation error.");
}
}
int main(int argc, char *argv[]){
char c;
int number = 0;
int result = 0;
char next_operation = '+';
do {
c = getchar();
if( c >= '0' && c <= '9' ){
number = number * 10 + c - 48;
} else if (c == '+'){
do_operation(next_operation, &result, &number);
next_operation = '+';
} else if (c == '-'){
do_operation(next_operation, &result, &number);
next_operation = '-';
} else {
do_operation(next_operation, &result, &number);
}
} while (c != '\n');
printf("%d", result);
}

How can I extract an integer from within a string?

I'm working on an assignment and as part of it I need to extract the integer from a string.
I've tried using the atoi() function, but it always returns a 0, so then I switched up to strtol(), but it still returns a 0.
The goal is to extract the integers from the string and pass them as arguments to a different function. I'm using a function that then uses these values to update some data (update_stats).
Please keep in mind that I'm fairly new to programming in the C language, but this was my attempt:
void get_number (char str[]) {
char *end;
int num;
num = strtol(str, &end, 10);
update_stats(num);
num = strtol(end, &end, 10);
update_stats(num);
}
The purpose of this is in a string "e5 d8" (for example) I would extract the 5 and the 8 from that string.
The format of the string is always the same.
How can I do this?
strtol doesn't find a number in a string. It converts the number at the beginning of the string. (It does skip whitespace, but nothing else.)
If you need to find where a number starts, you can use something like:
const char* nump = strpbrk(str, "0123456789");
if (nump == NULL) /* No number, handle error*/
(man strpbrk)
If your numbers might be signed, you'll need something a bit more sophisticated. One way is to do the above and then back up one character if the previous character is -. But watch out for the beginning of the string:
if ( nump != str && nump[-1] == '-') --nump;
Just putting - into the strpbrk argument would produce false matches on input like non-numeric7.
If the format is always like this, then this could also work
#include <stdio.h>
int main()
{
char *str[] = {"a5 d8", "fe55 eec2", "a5 abc111"};
int num1, num2;
for (int i = 0; i < 3; i++) {
sscanf(str[i], "%*[^0-9]%d%*[^0-9]%d", &num1, &num2);
printf("num1: %d, num2: %d\n", num1, num2);
}
return 0;
}
Output
num1: 5, num2: 8
num1: 55, num2: 2
num1: 5, num2: 111
%[^0-9] will match any non digit character. By adding the * like this %*[^0-9] indicates that the data is to be read from the string, but ignored.
I suggest you write the logic on your own. I know, it's like reinventing the wheel, but in that case, you will have an insight into how the library functions actually work.
Here is a function I propose:
bool getNumber(str,num_ptr)
char* str;
long* num_ptr;
{
bool flag = false;
int i = 0;
*num_ptr = 0;
char ch = ' ';
while (ch != '\0') {
ch = *(str + i);
if (ch >= '0' && ch <= '9') {
*num_ptr = (*num_ptr) * 10 + (long)(ch - 48);
flag = true;
}
i++;
}
return flag;
}
Don't forget to pass a string with a \0 at the end :)

Error in my string passing into the function which is a pointer in C?

Instruction: Alright, I am working on a code where I am doing number conversions. I am prompting the user to give me a base and an input of bits with a mathematic symbol such as '+', '-', '*' etc, and I do the calculation, if you have a strategy for that, then feel free to give me an idea.
Problem: Regardless, I am working on some strategy on how to do it, but I am having trouble with my character, strings, char pointers. I don't know how to resolve it. I hardly understand what pointers are, besides a location in memory. I need help resolving this problem.
baseToDec Function: Anyways, I have a method/function called baseToDec, where I perform a conversion from bits to a decimal and return an int. Inside those parameters, I have a char* which takes in the value. such as '1001' which is the value 9.
Ways: However, when I put in the string "first" inside that parameter down in my main, I get a fault segmentation. I don't know how to declare that string value where I won't get warnings or a segmentation fault. I've tried changing the variable to be a char *first, I tried to do the address. I don't understand it. I would like to know how I can do it so I don't get a warning and it returns an integer smoothly.
int baseToDec(int base, char* value)
{
int len = strlen(value);
int power = 1, result = 0,i, j, num;
if(base > 2) //not binary
{
for (i = len - 1; i >= 0; i--)
{
result += number(value[i]) * power;
power = power * base;
}
}
else if(base = 2)
{
while(value[i] == '0' || value[i] == '1' )// (2) remove the most significant binary digit(leftmost) and add it to the result.
{
if(value[i] == '1')
{
result = result * 2 + 1;
}
else if(value[i] == '0')
{
result *= 2;
}
i++;
} // (3) If all binary digits have been removed, you're done. Stop.
}
return result;
}
int main()
{
int base, i = 0, j =0, dec; // dec is declared here.
char input[100], first[100], second[100];
char option;
instructions();
scanf("%s", &option);
while(option != 'q')
{
i = 0;
printf("Base: ");
scanf("%d", &base);
printf("Input: ");
scanf("%s", input);
while(input[i] != '+' && input[i] != '-' && input[i] != '*' && input[i] != '/')
{
i++;
}
printf("%d", i);
if(input[i] == '+')
{
for(j = 0; j < i; j++)
{
first[j] = input[j];
}
first[i] = 0;
dec = baseToDec(base, first); // Error takes place here.
}
}
I know it's a lot of writing, but I listed where the errors take place and the method I pass.
This is wrong:
scanf("%s", &option);
When you use %s, you have to provide a pointer to a string that can hold the entire input. option is a char, not a string. It only has room for a single character, but %s writes the input word followed by a null terminator.
Use %c format to read a single character.
scanf(" %c", &option);
Also,
if (base = 2)
should be
if (base == 2)
But there's no need to treat binary differently from any other base, the conversion process is the same.

Calculating mathematical expressions in C using getchar()

I have been assigned with a school task.
In this task I have to create a program in C language that reads as an input from the user a mathematical expression and returns the result of it. For example the input must be something like 30 + 400 and the output must be in this case the result of the addition of 30 and 400 which is 430.The program must calculate apart from the addition and the other mathematical operations(subtraction,multiplication,division).Each expression must be read in one line and also I am not allowed to use arrays or any other complex data structure in my code.
I have tried some methods to solve this task but i can't understand how to separate the numbers from the operators so the expression can be calculated.
Here is the i have written:
#include <stdio.h>
int main(){
int ch,result;
int plus;
int minus;
int mult;
int div;
while((ch = getchar())!= EOF){
plus = 0;
minus = 0;
mult = 0;
div = 0;
if (ch != '\n'){
if (ch >= '0' && ch <='9'){ //Checks if the character is a number
result += ch;
}else if(ch== '+'){//Checks if the character is an operator
plus =1;
}else if(ch== '-'){
minus = 1;
}else if(ch == '*'){
mult = 1;
}else if(ch== '/'){
div = 1;
}
}
printf("%d\n",result);
}
}
Any suggestions or ideas would be very helpful.
P.S. I am sorry for my English and if I dint use the appropriate terms to describe this problem .
getchar returns the ASCII value you need to convert it into decimal.
You can use two integers to store the inputted numbers and act on it.
Example:
int num1 = 0,num2 = 0;
char op;
int state = 0;
while((ch = getchar())!= EOF){
if (ch != '\n'){
if (ch >= '0' && ch <='9'){ //Checks if the character is a number
if (state == 0)
num1 = num1*10 + ch- '0'; // Convert ASCII to decimal
else
num2 = num2*10 + ch- '0'; // Convert ASCII to decimal
}else {
/* Operator detected now start reading in second number*/
op = ch;
state = 1;
}
}
else {
int result =0;
switch(op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
}
printf("%d\n",result);
num1 = 0;
num2 = 0;
state = 0;
}

In C How to use leftmost digit from an integer

I was wondering how to reverse my output to match entered number.
Example if user entered 543210, I want the output to be: Five Four Three Two One Zero. But instead it's reversed and I can't figure out how to reverse it.
I can't use loops or anything else.
Code:
int main(void){
int value;
int digit;
printf("enter:");
scanf("%i", &value);
while(value)
{
digit = value % 10;
value = value / 10;
if(digit != 0)
{
switch(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;
}
}
}
return 0;
}
Exmaple: If user entered 1234
Output would be: four three two one.
How would I fix it to be: One Two Three Four.
Since you've said that you aren't allowed to use loops, then recursion really is the thing that you are probably being expected to use. I personally am not sure if it would be right to not consider a recursion as a loop, but whatever.
You are using a while there, which also is a loop. If you are allowed to use loops, then you could just do the following, easy-to-understand modification in your code, and get the output you desire:
...
int input; // <-- added this
int value;
int digit;
printf( "enter:" );
scanf( "%i", &input ); // <-- notice the change in variable usage
value = 0;
while ( input ) {
value = 10 * value + input % 10; // adds the last digit of input to value from right
input /= 10;
}
while ( value ) { ... }
...
If you aren't allowed to use loops, then you probably are expected to use a special function, a function which outputs a specific value for a single case, and returns back to itself in any other case. You need a recursive function. Examine this simple example:
// This is in maths, not C
f(x) = 2x + 1 for all integer x >= 0
Out of many ways, this one way to describe the function which maps 0 to 1, then 1 to 3, then n to 2n + 1. If we wanted to define the exact same function recursively:
// In maths
f(x = 0) = 1 for x = 0
f(x > 0) = f(x-1) + 2 for integer x > 0
You see what's going on in there? It's saying that each subsequent f(x) is 2 greater than the previous one f(x-1). But more importantly, the function is calling itself! If you look closer, the called function f(x-1) will also call itself:
f(x) = f(x-1) + 2
f(x) = f(x-2) + 2 + 2
f(x) = f(x-3) + 2 + 2 + 2
...
// all these are the same
All this calling deeper and deeper has to end somewhere, and that somewhere is when f(x-...) is f(0), which has been explicitly defined to be 1.
This is what recursion is all about. Let me write out the examples I gave above in C:
// non-recursive version
int fnonrec( int x ){
return 2 * x + 1;
}
// recursive version
int frec( int x ){
if ( x == 0 )
return 1; // explicit return value for f(0)
else // redundant else, hehe
return frec( x - 1 ) + 2;
}
Definitions of the functions really look similar to how they were defined in maths, don't they? Yeah, well, I don't think giving you the answer for your question would be nice of me. All I can say is that you can print things in reverse really nicely with recursive functions.
//store user input to int variable "value"
char str[15];
sprintf(str, "%d", value);
You can then use the strrev function to reverse the string array. Manipulate it from there.
#include <stdio.h>
void print(int v){
static char *numbers[] = {
"zero","one","two","three","four",
"five","six","seven","eight","nine"
};
int digit = v % 10;
int value = v / 10;
if(value){
print(value);
printf(" %s", numbers[digit]);
} else
printf("%s", numbers[digit]);
}
int main(void){
int value;
printf("enter:");
scanf("%i", &value);
print(value);
return 0;
}
Example using recursive function and numbers from the parameters :
#include <stdio.h>
void display(char c)
{
char *numbers[] = {
"zero","one","two","three","four",
"five","six","seven","eight","nine "
};
printf("%s ", numbers[c]);
}
int aff_num(char *c)
{
if (*c == '\0')
return (0);
display(*c-48);
aff_num(++c);
return (1);
}
int main(int argc, char **argv)
{
if (argc < 2)
{
printf("Need numbers\n");
return (-1);
}
aff_num(argv[1]);
return (0);
}
I'm a python hacker and I almost never program in C. that being said:
#include <stdlib.h>
#include <stdio.h>
int highest_power_of_ten(int value){
int exponent = 0;
int tens = 1;
while(value > tens){
tens *= 10;
exponent += 1;
}
return exponent-1;
}
int pow(int base, int exponent){
if (exponent == 0)
return 1;
int temp = base;
while(exponent > 1){
base *= temp;
exponent -= 1;
}
return base;
}
int main(int argc, char** argv){
char* digits[] =
{"zero","one","two","three","four","five","six","seven","eight","nine"};
int value, n, exp, x;
scanf("%i", &value);
while(highest_power_of_ten(value)>0){
exp = highest_power_of_ten(value);
x = pow(10, exp);
n = value/x;
printf("%s ",digits[n]);
value -= n*x;
}
printf("%s\n", digits[value]);
//system("PAUSE"); for windows i guess
return 0;
}
Another method to get the digits in the right order:
E.g. To get the digit at 1st position in 123 divide 123 by 100, to get 2nd - 123 / 10, to get 3rd 123 / 1. That equals: value / 10^(index of desired digit)
So what we have to do is
Get the length of the (remaining) number by calculating log10(value).
Then get the (remaining) first (most significant) digit by dividing value by 10^length (length of 1.)
calculate value := value - 10^length and start from 1, unless the result is 0 (mind handeling numbers that end on 0).
while (value)
{
len = log10(value);
digit = (int) value / pow(10, len);
value -= pow(10, len);
}
And your code does never enter case 0. To fix that just leave the if(digit != 0) - that's what I meant when I wrote "mind the 0").
if(digit != 0) // enters if digit is not 0
{
switch(digit)
{
case 0: // enters if digit is 0
...
}
}

Resources