0

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;
}
alessandrio
  • 4,282
  • 2
  • 29
  • 40
NoaRoth
  • 29
  • 4

4 Answers4

0

As Sourav Ghosh mentioned this is definetly post for Code Review. But since you already wasted your time posting here, I would advise you read up this:

Please explain the output of sizeof()

I am not quite sure why you defined your own function when you could have used the sizeof operator which do exactly what your function is doing.

Edit:

Another good example

Edint 2.0 : The warning you got is the compiler basicly saying, "What will happen if neither of your cases are matched?" . In more simple words it asks for a else case in which to go in the scenario where none of the if's match the case.

Regarding how to write the value to a file, you can use fprintf();

FILE *f = fopen("file.txt", "w");
 if (f == NULL)
{
  printf("Error opening file!\n");
  exit(1);
}
int i = 1;
fprintf(f,"%d", i);
fclose(f);

More information and examples for fprintf

du4ko
  • 101
  • 6
  • but if I use sizeof I get a wrong output (I have checked it in my code) – NoaRoth Jun 01 '17 at 13:52
  • Can you provide me with an example of how you used it , what did it return, and what did you expected? – du4ko Jun 01 '17 at 13:57
  • Actually the only wrong value here is the char value, the pointer **cprt** is supose to be 4, in the array it **caaray[]** is supose to be 80, but since char is 4 it is 320. Do you use structure in your code, please provide me with the code of you checking how sizeof operator works. Here on my side just returned sizeof(char) = 1; sizeof(char*point) = 4; sizeof(char[80]) = 80; – du4ko Jun 01 '17 at 14:55
  • I dont use structures in my code...I really dont understand what is going wrong in my code.. – NoaRoth Jun 01 '17 at 15:14
  • I have just how sizeof operator wrong, and the get the output 1 for sizeof(char) – NoaRoth Jun 01 '17 at 15:23
  • There are cases when not properly defined char size changes to 4. I am currently AFK when i get back home i will give you example. – du4ko Jun 01 '17 at 15:27
  • Sorry i didnt quite understood your last comment did you get sizeof(char) = 1? – du4ko Jun 01 '17 at 15:28
  • If you don't need any more help I would appretiate if you found me helpfull to upvote/accept my answer. Thanks! – du4ko Jun 01 '17 at 15:54
  • I do need more help, becuase I get a wrong output in my code above! – NoaRoth Jun 01 '17 at 15:57
  • What is the output? Edit your post with the latest code. – du4ko Jun 01 '17 at 16:01
  • see below please – NoaRoth Jun 01 '17 at 16:03
  • Once i get home i will debug it :) – du4ko Jun 01 '17 at 16:07
0

I have changed my code by using sizeof and I get a wrong output.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

void bytesPerValue(char str[]);
 int strToNumber(char *str);

void main()
{
     char str[50];
                        gets(str);

                        bytesPerValue(str);

}

void bytesPerValue(char str[]) 
{
        int i = 0, j = 0;
        int temp = 1;
        int size;
        char* tempChar = (char*)malloc((strlen(str))*sizeof(tempChar));
        while (str[i]!=' ' || str[i]=='*') //checking the type of the variables//
        {
                tempChar[j] = str[i];
                i++;
                j++;   
        }
        tempChar[j] = '\0';
        size = sizeof(tempChar);
        j = 0;
        i++;
        while (str[i] != ';')
        {

                if (isalpha(str[i]) || str[i]=='_') // for  variables and arrays//
                {
                        while (str[i] != ',' && str[i] != ';') //runs until ', ' or '; ' //
                        {
                                if (str[i]==' ')
                                {
                                        while (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 in order to 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 (str[i]==' ')
                                {
                                        while (str[i]==' ')
                                                i++;
                                }
                        }
                        printf(" requires %d bytes \n", 4);
                }
                if (str[i] != ';')
                        i++;
        }


}

For example, for the following input: char c, *cprt, carray[80]; I get the following output: c requires 4 bytes *cprt requires 4 bytes caaray[] requires 320 bytes

which is wrong...

NoaRoth
  • 29
  • 4
  • `size = sizeof(tempChar);` : `sizeof(tempChar)` is pointer (`tempChar`) size. You need parsed type size. – BLUEPIXY Jun 01 '17 at 17:00
  • how shall I do it? – NoaRoth Jun 01 '17 at 17:07
  • You retreated from the previous method. parse , validation and evaluate. BTW Do you accept 2D-Array or more? – BLUEPIXY Jun 01 '17 at 17:12
  • sorry, I do not understand your answer...and I do not accept 2d array or more. – NoaRoth Jun 01 '17 at 17:17
  • There are various ways of thinking from a simple method to an exact method. So simply can not affirm "Do it like this". BTW Do you accept double pointer or more? (like `char **strp;`) – BLUEPIXY Jun 01 '17 at 17:38
  • no, I dont accept double pointer or more. only what is shown above, – NoaRoth Jun 01 '17 at 17:49
  • There is no explanation about arrays and pointers in your explanation(_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._). It only has to analogize from the code. – BLUEPIXY Jun 01 '17 at 17:52
0

I have just edited my code, not using sizeof. I also add a use of file in my code. I think it works well now. I would be happy if you may please tell me what you think about it, whether my code should be improved or fixed.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

void bytesPerValue(char str[], char* filename) ;
int theSizeOf(char *str);
 int strToNumber(char *str);

void main()
{
     char str[50];

     gets(str);

     bytesPerValue(str,"input.txt");

}

void bytesPerValue(char str[], char* filename) 
{
        int i = 0, j = 0;
        int temp = 1;
        int size;
        char* tempChar = (char*)malloc((strlen(str))*sizeof(tempChar));
        FILE *f=fopen(filename,"w");
        if (f==NULL)
            exit(1);
        while (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  variables and arrays//
                {
                        while (str[i] != ',' && str[i] != ';') //runs until ', ' or '; ' //
                        {
                                if (str[i]==' ')
                                {
                                        while (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 in order to valuate the bytes//
                                }
                                printf("%c", str[i]);
                                i++;

                                if (isspace(str[i]))
                                {
                                        while (isspace(str[i]))
                                                i++;
                                }
                        }
                        fprintf(f," requires %d bytes \n", temp*(sizeof(temp)));
                }


                if (str[i] == '*') //for pointers//
                {
                        while (str[i] != ',' && str[i] != ';')
                        {
                                printf("%c", str[i]);
                                i++;
                                if (str[i]==' ')
                                {
                                        while (str[i]==' ')
                                                i++;
                                }
                        }
                        fprintf(f," requires %d bytes \n", 4);
                }
                if (str[i] != ';')
                        i++;
        }

 fclose(f);
}

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;
        else if (strcmp(str, "char")==0)
                return 1;
        else if (strcmp(str, "double")==0)
                return 8;
        else if (strcmp(str, "short")==0)
                return 2;
        else 
            return 0;
}


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;
} 

thank you all for your help!

NoaRoth
  • 29
  • 4
  • `printf("%c", str[i]);` --> `fprintf(f, "%c", str[i]);`, `fprintf(f," requires %d bytes \n", temp*(sizeof(temp)));` --> `fprintf(f," requires %d bytes \n", temp*size);` – BLUEPIXY Jun 01 '17 at 23:56
0

example of using sscanf.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFF_SIZE 128

void bytesPerValue(FILE *ofp, char str[]);

int main(int argc, char *argv[]){
    char str[BUFF_SIZE];
    char *inp_filename, *out_filename;
    FILE *ifp, *ofp;

    if(argc != 3){
        fprintf(stderr, "Usage: %s input_filename output_filename\n", argv[0]);
        return EXIT_FAILURE;
    }

    inp_filename = argv[1], out_filename = argv[2];
    if(NULL==(ifp = fopen(inp_filename, "r"))){
        fprintf(stderr, "Couldn't open file : %s\n", inp_filename);
        return EXIT_FAILURE;
    }
    if(NULL==(ofp = fopen(out_filename, "w"))){
        fprintf(stderr, "Couldn't open file : %s\n", out_filename);
        return EXIT_FAILURE;
    }

    while(fgets(str, sizeof str, ifp)){
        //str[strcspn(str, "\n")] = 0;//chomp newline
        bytesPerValue(ofp, str);
    }
    fclose(ifp), fclose(ofp);
}

struct size_of_type {
    const char *name;
    int size;
} Type_size[] = {
    { "char"  , sizeof(char) },
    { "double", sizeof(double) },
    { "float" , sizeof(float) },
    { "int"   , sizeof(int) },
    { "long"  , sizeof(long) },
    { "short" , sizeof(short) },
};

int cmp(const void *a, const void *b){
    return strcmp(*(char **)a, *(char **)b);
}

int theSizeOf(const char *type){
    struct size_of_type *stp;
    if(!*type)//""
        return 0;
    stp = bsearch(&type, Type_size, sizeof(Type_size)/sizeof(*Type_size), sizeof(*Type_size), cmp);
    return stp ? stp->size : -1;
}

enum { UNKNOWN = -1, NONE };
#define UNDER_BAR "_"
#define UPPERCASE "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#define LOWERCASE "abcdefghijklmnopqrstuvwxyz"
#define ID_CHARS  UPPERCASE LOWERCASE UNDER_BAR

void bytesPerValue(FILE *fp, char str[]) {
    char type[16] = "", rest[BUFF_SIZE];
    char field[BUFF_SIZE], id[BUFF_SIZE], dummy[BUFF_SIZE];
    char *sp, sep=0, end_b, dispname[BUFF_SIZE];
    int typeSize, size, subscript, len;

    sscanf(str, "%s %[^\n]", type, rest);
    typeSize = theSizeOf(type);
    if(typeSize == UNKNOWN){
        fprintf(fp, "%s is unknown type in '%s'\n", type, str);
        return;
    } else if(typeSize == NONE){//blank line
        return;
    }
    sp = rest;
    for(sp = rest; 2 == sscanf(sp, " %[^,;]%c%n", field, &sep, &len) && (sep == ',' || sep == ';'); sp += len){
        if(3 == sscanf(field, " * %[" ID_CHARS "] [%d %c %s", id, &subscript, &end_b, dummy) && subscript > 0 && end_b == ']'){//array of pointer
            typeSize = sizeof(void *);
            size = typeSize * subscript;
            sprintf(dispname, "*%s[]", id);
        }
        else if(3 == sscanf(field, " %[" ID_CHARS "] [%d %c %s", id, &subscript, &end_b, dummy) && subscript > 0 && end_b == ']'){//array
            size = typeSize * subscript;
            sprintf(dispname, "%s[]", id);
        }
        else if(1 == sscanf(field, " * %[" ID_CHARS "] %s", id, dummy)){//pointer
            size = typeSize = sizeof(void *);
            sprintf(dispname, "*%s", id);
        }
        else if(1 == sscanf(field, " %[" ID_CHARS "] %s", id, dummy)){//normal variable
            size = typeSize;
            strcpy(dispname, id);
        } else {
            fprintf(fp, "'%s' is invalid format.\n", field);
            continue;
        }
        fprintf(fp, "%s requires %d bytes \n", dispname, size);
    }
    if(sep != ';'){
        fprintf(fp, "'%s' is invalid format.\n", str);
    }
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70