Calculator - Converting Float Result to String SResult for Printf-ing

A calculator. Very, VERY basic. Trying to convert a float to string.

Page 1 of 1

14 Replies - 2401 Views - Last Post: 18 February 2010 - 02:12 AM Rate Topic: -----

#1 Nineza  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 17-February 10

Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 12:37 PM

Well, currently I have a script in C. I am using Microsoft Visual C++ 2008 Express Edition.
Here's the script so far:

// Calculator.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string>

using namespace std;


float GetNumber()
{
	float GetNumber=0;
	printf("Please input a number:\n");
	scanf_s("%c", &GetNumber);
	getchar();
	return(GetNumber);
}

char GetOperator()
{
	char GetOperator=0;
	printf("Please input an operator:\n");
	scanf_s("%c", &GetOperator);
	getchar();
	return(GetOperator);
}

int main()
{
	printf("Welcome to my Calculator!\n");
	printf("Please do what is said below:\n\n");
	float a = GetNumber();
	printf("\n\n");
	getchar();
	char b = GetOperator();
	printf("\n\n");
	float c = GetNumber();
	
	float result;
	if(b == '+')
	{
		result = a + c;
	}
	else if(b == '-')
	{
		result = a - c;
	}
	else if(b == '*')
	{
		result = a * c;
	}
	else if(b == '/')
	{
		result = a / c;
	}
	printf("\n\nThe result of these is: ");
	string sresult;
	sprintf(sresult, "%f", result);
	printf(sresult);
	getchar();
	
	return 0;
}


It is very, VERY basic since I only started C a few days ago, with the help of a friend to learn a few of these functions etc.
I am struggling, since I'm trying to make it so that you write in a number, then an operator, then a number. I know I've probably gone wrong somewhere else, or I've made it very easy to break, or I could make it more efficient by ..., but I'm just trying to fix this error at the moment:

1>********\visual studio 2008\projects\calculator\calculator\calculator.cpp(58) : error C2664: 'sprintf' : cannot convert parameter 1 from 'std::string' to 'char *'
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>********\visual studio 2008\projects\calculator\calculator\calculator.cpp(59) : error C2664: 'printf' : cannot convert parameter 1 from 'std::string' to 'const char *'
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called


I didn't have any changing method before, just it trying to use printf on a float, but since it gave an error for that, I went looking about. I had a look at quite a few things. So, that's what I have at the moment.

Please can someone help me to fix these errors?

Thanks in advance,
A new C coder,
Nineza.

Is This A Good Question/Topic? 0
  • +

Replies To: Calculator - Converting Float Result to String SResult for Printf-ing

#2 bodom658  Icon User is offline

  • Villiage Idiom
  • member icon

Reputation: 113
  • View blog
  • Posts: 1,123
  • Joined: 22-February 08

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 12:46 PM

try using cout statements instead of printf. They can be found by including iostream. These objects are built to be compatible with C++ string objects, while printf is not.

Just so you know,
printf("%s", myString);

becomes
cout << myString;


Cheers,
Bodom

This post has been edited by bodom658: 17 February 2010 - 12:47 PM

Was This Post Helpful? 1
  • +
  • -

#3 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 12:49 PM

You have mixed C and C++ code. Ordinarily, this is not such a problem, but the two errors you have are caused by these three lines of code.

        string sresult; 
        sprintf(sresult, "%f", result); 
        printf(sresult); 



What you shoudl do here is this:

        printf("%f", result);



What this is saying to the routine printf, there is one additional parameter that I am giving you and it's a float. printf will then print the value of the floating point number. This is what you were trying to achieve anyway!

If you remove the #include <string>, and replace it with #include <string.h>, then you will not be tempted to use the string class (C++) in your program which is pure C.

Another small thing for you to consider is the return statement. The syntax you have used i.e. return(expression); has been deprecated for many years, and although it still works, it is a bad thing to get into the habit of using stuff that is no longer used. Simply say return expression; (e.g. return GetOperator;)

Hope that helps.

Whilst what bodom658 has just posted in not wrong, as 98% of your program is pure C, you might as well leave it as such and implement the changes I have suggested.

This post has been edited by Martyn.Rae: 17 February 2010 - 12:51 PM

Was This Post Helpful? 0
  • +
  • -

#4 Nineza  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 17-February 10

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 12:57 PM

Oh! I already knew about cout and that they're in iostream and they're C++, but my friend said you shouldn't mix up the languages, so I decided not to use that. But I'll try it. Thanks! ;)

I'll reply once tested. ;)

View PostMartyn.Rae, on 17 February 2010 - 11:49 AM, said:

You have mixed C and C++ code. Ordinarily, this is not such a problem, but the two errors you have are caused by these three lines of code.

        string sresult; 
        sprintf(sresult, "%f", result); 
        printf(sresult); 



What you shoudl do here is this:

        printf("%f", result);



What this is saying to the routine printf, there is one additional parameter that I am giving you and it's a float. printf will then print the value of the floating point number. This is what you were trying to achieve anyway!

If you remove the #include <string>, and replace it with #include <string.h>, then you will not be tempted to use the string class (C++) in your program which is pure C.

Another small thing for you to consider is the return statement. The syntax you have used i.e. return(expression); has been deprecated for many years, and although it still works, it is a bad thing to get into the habit of using stuff that is no longer used. Simply say return expression; (e.g. return GetOperator;)

Hope that helps.

Whilst what bodom658 has just posted in not wrong, as 98% of your program is pure C, you might as well leave it as such and implement the changes I have suggested.

@Martyn Erm, what does adding the .h bit on edit? I didn't know it would do anything... Also, simply say return GetNumber; , instead of return(GetNumber); ? Wow, small differences make big changes. xD

I'll try Martyn's fix first. :)

New error: ********\visual studio 2008\projects\calculator\calculator\calculator.cpp(7) : error C2871: 'std' : a namespace with this name does not exist
Should I remove the "using namespace std" thing at the top? :)

Well, I removed the using namespace std thingy, but the only problem was, I wrote in 16 for the first number, then * for the operator, then 2 for the second number. It should've come out as 32, but it came out as:
0.000000 (Yes, that IS the correct number of zeros).

Erm, what should I do now? I'm confused. :S
Was This Post Helpful? 0
  • +
  • -

#5 bodom658  Icon User is offline

  • Villiage Idiom
  • member icon

Reputation: 113
  • View blog
  • Posts: 1,123
  • Joined: 22-February 08

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 12:58 PM

Absolutely, if you want to use pure C, and are not using C++ headers, there is no need for that line.
Was This Post Helpful? 0
  • +
  • -

#6 Nineza  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 17-February 10

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 12:59 PM

Okay. Thanks.

But now there's a new problem (NOTE: Not error, bug)!
Well, I removed the using namespace std thingy, but the only problem was, I wrote in 16 for the first number, then * for the operator, then 2 for the second number. It should've come out as 32, but it came out as:
0.000000 (Yes, that IS the correct number of zeros).

Erm, what should I do now? I'm confused. :S
Was This Post Helpful? 0
  • +
  • -

#7 bodom658  Icon User is offline

  • Villiage Idiom
  • member icon

Reputation: 113
  • View blog
  • Posts: 1,123
  • Joined: 22-February 08

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 01:05 PM

Take a look at how you are reading the number in in your GetNumber function. You appear to be reading it in as a character. This will defiantly cause some issues. I'd suggest reading them in as floats instead, by using %f instead of %c. Also, rename your float variable inside GetNumber and update it as needed. You should not have more than one function or variable as the same name in the same scope. Make sure you also update this new name in your scan and return statements.
Was This Post Helpful? 0
  • +
  • -

#8 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 01:08 PM

In your getNumber routine, you have said

 scanf_s("%c", &GetNumber);



It should be "%f".

The code then works!

I forgot to address your question Nineza. The <string.h> file is the C include file, whereas the <string> include file is the string class definition.

@bodom658 - that is perfectly ok, the function name is only used on the outside of the function. Once the compiler is parsing and generating code for the function it does not care if a variable has the name name as the function. It can be quite useful to highlight the variable that is going to be returned to the caller.

This post has been edited by Martyn.Rae: 17 February 2010 - 01:13 PM

Was This Post Helpful? 0
  • +
  • -

#9 Nineza  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 17-February 10

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 01:09 PM

I didn't know about the %f and %c thing. I was just using something my friend gave me for a multiple choice game where you type in a character, I thought it might be the same... Well, thanks. My calculator now works. This is not an error, but its something I'd like to clean up:

It always puts it to 6 decimal places. How do I make it so if the answer is 32, it only displays 32, and if the answer is 32.6, it displays 32.6 etc? Is there a way?

Thanks for all your help! ;)
Was This Post Helpful? 0
  • +
  • -

#10 bodom658  Icon User is offline

  • Villiage Idiom
  • member icon

Reputation: 113
  • View blog
  • Posts: 1,123
  • Joined: 22-February 08

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 01:19 PM

Martyn may know more, but as far as I know you can only limit the number you are printing out statically.

Say you wanted to print out the number and the first decimal place.

You would use this in your print statement for the placeholder:
%0.1f



@Martyn.Rae Thanks for clearing that up! I'm guessing then that the compiler can differentiate between the variable and the function in the event of a recursive function... Which makes sense because the compiler is probably, in the end, only concerned with where the function (list of operations) is in memory, and the generated executable will call it via it's address. Logically thinking, anyway.
Was This Post Helpful? 0
  • +
  • -

#11 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 01:22 PM

I don't think there is a way. What you could do is say

    if ( floor(result) != result )
       printf("%.2f", result); // Print floating point number to 2 decimal places
    else
       printf("%d", result);   // Print decimal number (the compiler will generate
                               // the code for the conversion from float to
                               // integer



The problem with that code is that very small fractions such as 32.00001 would floor to 32.00000, and yet 32.00001 is not equal to 32.00000. In other words you may still get 32.00 as a printed value.

Hope that helps.
Was This Post Helpful? 0
  • +
  • -

#12 sarmanu  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 966
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 01:27 PM

There is a way. Use %g instead of %f:
printf("%g", my_float);


This represents the "short version" of a float.
EXAMPLE:
#include <stdio.h>

int main()
{
	float a = 32.20000;
	printf("%f\n", a); // prints 32.20000
	printf("%g\n", a); // prints 32.2
        float b = 32;
        printf("%f\n", B)/>; // prints 32.00000
        printf("%g\n", B)/>; // prints 32

	return 0;
}


This post has been edited by sarmanu: 17 February 2010 - 01:32 PM

Was This Post Helpful? 1
  • +
  • -

#13 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 01:33 PM

@sarmanu, I had forgotten about %g. It's been a little while since I dealt with printf, floats and doubles :genius:
Was This Post Helpful? 0
  • +
  • -

#14 Nineza  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 24
  • Joined: 17-February 10

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 17 February 2010 - 01:33 PM

Wow. It works! Thanks. ;)

I also added a from degrees to radians thing in my calculator. And, when you write in 'r' as the operator, it doesn't force you to write in the second number. =D
I might make a reverse, and from degrees to graduals or w.e they are out of 200. xD

Thanks! Your help was really useful. ;)
Was This Post Helpful? 0
  • +
  • -

#15 Martyn.Rae  Icon User is offline

  • The programming dinosaur
  • member icon

Reputation: 540
  • View blog
  • Posts: 1,406
  • Joined: 22-August 09

Re: Calculator - Converting Float Result to String SResult for Printf-ing

Posted 18 February 2010 - 02:12 AM

For recursive functions, no it can't. What it does is to take the variable name and say ok, this is what is being called. Ahhh, it's a function with no arguments and cause an error.

So

float GetNumber() 
{ 
        float GetNumber=0; 
        printf("Please input a number:\n"); 
        scanf_s("%f", &GetNumber); 
        getchar(); 
	return GetNumber(); 
} 



will fail which is correct. However, it is actually the programmer that is incorrect! You need to think outside the box ... literally. We want to call the GetNumber function, not the internal GetNumber. To do this of course you simply apply the global scope operator thus:

float GetNumber() 
{ 
        float GetNumber=0; 
        printf("Please input a number:\n"); 
        scanf_s("%f", &GetNumber); 
        getchar(); 
	return ::GetNumber(); 
} 



and there is no confusion ... the compiler compiles it and generates the correct code.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1