Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

something is wrong with my code, again.

+1 vote
asked Dec 30, 2022 by codenxn (1,250 points)

Hi! Sorry for asking so much but I got an error while trying to make a calculator program in C. I used everything the internet told me to, like the strcmp() function in "if"s, etc, but it doesn't want to work. I also tried the usual ==  for comparing strings, still, doesn't works.

2 Answers

+3 votes
answered Dec 30, 2022 by Peter Minarik (66,990 points)
edited Dec 31, 2022 by Peter Minarik
 
Best answer
  • You should include ctype.h for tolower().
  • strcmp() returns 0 when the strings match, so check if the returned value is 0. If you don't do that, the default behaviour is to interpret the return value as a boolean. If it is a numeric value, anything that's 0 means false. Anything that's non-zero means true. That's why your code was broken.
  • You don't need the address-of operator (&) before an array of characters when you want to read string into this array.
#include <ctype.h>
#include <stdio.h>
#include <string.h>

int main() {
    char answer[100];
    printf("Hi! Welcome to my calculator project! Do you wanna calculate in int or a float? (int/float)\n");
    scanf("%s", answer);
    //Make the answer Lower case
    size_t length_of_answer = strlen(answer);
    for (size_t i = 0; i < length_of_answer; i++) {
        answer[i] = tolower(answer[i]);
    }
    if (strcmp(answer, "int") == 0) {
        printf("TEST: int");
    } else if (strcmp(answer, "float") == 0) {
        printf("TEST: float");
    } else {
        printf("Your answer is unrecognisable");
    }
    return 0;
}

Keep on learning! Good luck! :)

commented Dec 30, 2022 by codenxn (1,250 points)
OOOH, the last comment on my latest question said the same, i guess I was stupid enough to ignore it. I thought the "tolower" function comes with "string.h". Thank you =)
+2 votes
answered Dec 30, 2022 by Peter Minarik (66,990 points)

Can you share your code so others can have a look?

In C, you're supposed to use strcmp() to compare strings, not ==.

commented Dec 30, 2022 by codenxn (1,250 points)
commented Dec 30, 2022 by Peter Minarik (66,990 points)
See my answer above (formatting is not allowed in the comments, so I've rather replied via another answer).
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...