I'm very new to C programming and studying on K&R C Programming Language book. I'm trying to write a program converts hexadecimal numbers to decimal numbers repeatedly and want to use a function in my code. There are some problems prevent me from understanding C. I've read about them but not clearly understand.
I want to read input with length max 4, but as I understand scanf() doesn't limit length although the length of char array is 4. So I tried to eliminate non-integer characters with a for loop. Is this ok? What is the proper way of getting input from users? I don't want to use while((cr=getchar())!=EOF).
When I run the program, I get an error message:"undefined reference to 'convert'". How should I define functions?
I use Code::Blocks 16.01 and MinGW.
Here is my try:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#define LENGTH 4
int convert (char hex[]);
int result,validLength,j;
char input[LENGTH];
int main(){
while(1){
printf("Please enter valid hexadecimal number %d length:",LENGTH);
scanf("%c", input); //reading to char array
for(j=0;j<LENGTH;j++) // buffer
if(input[j] > 48 && input[j] < 58)
validLength++;
printf("Here is the decimal result: %d", convert(input[validLength]));
validLength=0;
}
int convert(char hex[]){
int t;
for(t=0; t < validLength; t++)
result= result+ hex[t]*(pow(16,(validLength-t)));
return result;
}
return 0;
}
int convert(char hex[]){ ... }move this to outside ofmain.convert(input[validLength])-->convert(input)scanf("%c", input);-->scanf(" %4c", input);input[j] > 48-->input[j] >= '0'isxdigitis there inctype.hfor you.