In: Computer Science
Syntax error in C. I am not familiar with C at all and I keep getting this one error "c error expected identifier or '(' before } token" Please show me where I made the error. The error is said to be on the very last line, so the very last bracket
#include
#include
#include
#include
int main(int argc, char*_argv[])
{
int input;
if (argc < 2)
{
input = promptUserInput();
}
else
{
input = (int)strtol(_argv[1],NULL, 10);
}
printResult(input);
return 0;
}
int promptUserInput()
{ int result;
printf("\nEnter a decimal number to convert: ");
scanf("%d\n", &result); // %d refers to an integer
return result;
}
char* decimalToOctal();
char* decimalToHex();
void printResult(int input)
{
char *octal; //referaece in the heap
char *hex; // reference in the heap
// char *binary // ref in the heap
octal = decimalToOctal(input);
hex = decimalToHex(input);
// binary = decimalToBinary(input);
printf("The decimal %d in octal is: %s \n", input, octal);
printf("The decimal %d in hex is: %s \n", input, hex);
// printf("The decimal %d in binary is: %s \n", input, binary);
free(octal); //free delocates the memory
free(hex);
// free(binary);
}
char* decimalToOctal(int input)
{
char* result;
result = (char*)malloc(sizeof(char)*(int)(log10(input)/log10(8)+1));
sprintf(result, "%o", input);
return result;
}
char* decimalToHex(int input)
{
char* result;
result = (char*)malloc(sizeof(char)*(int)(log10(input)/log10(16)+1));
sprintf(result, "%x", input);
return result;
}
}
Answer:
#include <stdio.h>
int main(int argc, char*_argv[])
{
int input;
if (argc < 2)
{
input = promptUserInput();
}
else
{
input = (int)strtol(_argv[1],NULL, 10);
}
printResult(input);
return 0;
}
int promptUserInput()
{
int result;
printf("\nEnter a decimal number to convert: ");
scanf("%d\n", &result); // %d refers to an integer
return result;
}
char* decimalToOctal();
char* decimalToHex();
void printResult(int input)
{
char *octal; //referaece in the heap
char *hex; // reference in the heap
// char *binary // ref in the heap
octal = decimalToOctal(input);
hex = decimalToHex(input);
// binary = decimalToBinary(input);
printf("The decimal %d in octal is: %s \n", input, octal);
printf("The decimal %d in hex is: %s \n", input, hex);
// printf("The decimal %d in binary is: %s \n", input, binary);
free(octal); //free delocates the memory
free(hex);
// free(binary);
}
char* decimalToOctal(int input)
{
char* result;
result = (char*)malloc(sizeof(char)*(int)(log10(input)/log10(8)+1));
sprintf(result, "%o", input);
return result;
}
char* decimalToHex(int input)
{
char* result;
result = (char*)malloc(sizeof(char)*(int)(log10(input)/log10(16)+1));
sprintf(result, "%x", input);
return result;
}
Note: Please check the updated code. You just have to remove the '}' in the last line.