Each input line should consist of - A type name, which must be one of the following: char, int, short, long, float, or double. - One or more individual declaration specifications separated by commas. - A semicolon marking the end of line.
The program should exit if it reads a blank input line.
I wrote the following code for this program. It seems to work well,except thefollowing warning I get :
d:\documents\documents\visual studio 2012\projects\project3\project3\source.c(108): warning C4715: 'theSizeOf' : not all control paths return a value.
By the way, I wonder if it can be improved (maby by using strtok?). I also would like to add a file in this program which is to contain the output and I am not sure at all how it has to be done.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
void bytesPerValue(char str[]);
int theSizeOf(char *str);
int strToNumber(char *str);
void main()
{
char str[50];
gets(str);
bytesPerValue(str);
}
void bytesPerValue(char str[]) //Ex5
{
int i = 0, j = 0;
int temp = 1;
int size;
char* tempChar = (char*)malloc((strlen(str))*sizeof(tempChar));
while (!isspace(str[i]) || str[i]=='*') //checking the type of the variables
{
tempChar[j] = str[i];
i++;
j++;
}
tempChar[j] = '\0';
size = theSizeOf(tempChar);
j = 0;
i++;
while (str[i] != ';')
{
if (isalpha(str[i]) || str[i]=='_') // for normal variables and arrays
{
while (str[i] != ',' && str[i] != ';') //runs until ', ' or '; '
{
if (isspace(str[i]))
{
while (isspace(str[i]))
i++;
}
if (str[i] == '[') //checks if it is array
{
printf("%c", str[i]);
i++;
while (str[i] != ']')
{
tempChar[j] = str[i]; //copies the value in the string
i++;
j++;
}
tempChar[j] = '\0';
temp = strToNumber(tempChar); //converting to number so I can valuate the bytes
}
printf("%c", str[i]);
i++;
if (isspace(str[i]))
{
while (isspace(str[i]))
i++;
}
}
printf(" requires %d bytes \n", temp*size);
}
if (str[i] == '*') //for pointers
{
while (str[i] != ',' && str[i] != ';')
{
printf("%c", str[i]);
i++;
if (isspace(str[i]))
{
while (isspace(str[i]))
i++;
}
}
printf(" requires %d bytes \n", 4);
}
if (str[i] != ';')
i++;
}
}
int theSizeOf(char* str) // checking the size of the variable
{
if (strcmp(str, "int")==0 || strcmp(str, "long")==0 || strcmp(str, "float")==0)
return 4;
if (strcmp(str, "char")==0)
return 1;
if (strcmp(str, "double")==0)
return 8;
if (strcmp(str, "short")==0)
return 2;
}
int strToNumber(char* str) //converting the string to number
{
int temp=1;
int num=0;
int t;
int i;
int length = strlen(str);
for (i = length-1; i >= 0; i--)
{
t = str[i] - '0';
num += t * temp;
temp *= 10;
}
return num;
}