Forum Thread: Printf() Not Printing My Value

Printf() Not Printing My Value

This code is C

printf(); in the first part of my if statement is not printing the second number i have, but a different one. For example i'll store 20 in it but printf(); will print 237005 when it comes time to print my variable value.

I have commented out my function add(); to see if that helps but it does not, i have read over the code multiple times and i do not see any problem with it. I am using the correct format specifier for the number i'm wanting to print out.

Any suggestions?


3 Responses

You need to check the value returned by strcmp:

if(strcmp(userinput1, "add") == 0)

The strcmp() function will return <0 or >0 if the strings do not match, otherwise it returns 0 if the strings do match.

I got it working to a fashion, but don't have the actual add(), etc functions to verify your program will work. But if you make those corrections ti should get you moving in the right direction.

Might be worth reading the man page for strcmp(), hope you get it working and happy coding.

Strange, i wouldn't think strcmp would have effected it if the first value printed out correctly. I looked into the strcmp function and i have learned it.

The function will return an integer less than 0 if string1 is less than string2, it will return a number greater than 0 if string one is greater than string 2 or it will return a value == 0 if both strings match in value.

The strings are compared using ASCII values.

Thank you for the help, i got my program working. Atleast with an included add(); function. Next time i'll have to pay more attention to the documents.

Technically, you are right. Your add function operates independently from your call to strcmp().

The problem is that your functions (add(), ETC) are only executed if the strcmp() function is evaluated somehow - so we compare the result from strcmp() looking for a 0...essentially, we're saying, if this string matches this one, do this.

We could do something like this if we wanted to be silly or just experiment:

if ((strcmp(string, "divide") != 0) && (strcmp(string, "multiply") != 0)) {
/* We know the only other option is add, so if we don't find either
* of multiply or divide we can sort of default to add()

What we're saying in the above statement is that is the string doesn't equal "divide" AND (the && part) the string doesn't equal "multiply" then do this.

I hope that helps, just play about with it and have fun and hope it helps.

Share Your Thoughts

  • Hot
  • Active