14,699,322 members
1.00/5 (1 vote)
See more:
I want to make a calculator in C including floats but without asking what is operation and numbers one by one .I mean user will write 3+2.5 and press enter and program will return 5.5

What I have tried:

I think I should use string for it but I couldn't make it.
Posted
Updated 16-Feb-20 0:05am

## Solution 1

That's actually quite a bit of work.
You need to read the user input as a string, and then process it into tokens - and how complex that process gets depends on how "full" your calculator is.
By that, I mean do you want to just process this:
`3+2.5`
Giving 5.5, Or do you want to process this:
`3+2.5*-4`
Giving -7.0?
The first example is fairly easy: process digits and a single full stop until you meet something that isn't and that's your first number. The thing that isn't is your operator, and then you look for the whole second number.
You can then convert the numbers to floating point values using the strtof function[^] and process the operator via a `switch`

The second version is a lot more work: you will need a stack (and probably to convert your whole expression to ReversePolish notation to make it easier to process). Google can help you there is you look for Calculator C - Google Search[^] and start reading!
v2

## Solution 2

Quote:
I think I should use string for it but I couldn't make it.

Since keyboard input can only be done with a string/buffer, the comment suggest you are very beginner.
A calculator with inline input is rather complicated. Pretty soon, you need to handle operators priority, sign operator, parenthesis ... and for this a parser with grammar.
A parser is not for absolute beginner, rather get experience before use.
Parsing - Wikipedia[^]
ANTLR - Wikipedia[^]
Using reverse polish notation will simplify input processing.
Reverse Polish notation - Wikipedia[^]

Advice: gain experience with smaller/simpler project before this project.

## Solution 3

The simplest way is to ask for the operation and than for two numbers, else it is a bunch of work.

When you want to do it in C it is a lot of work, because you have to do it all on your own. Higher languages as C++ have string classes which would help you. So consider using C++.

The first thing you have to do is to parse the input as string for numbers and for operators and than handle them correct.

you can access a char of a string with the [} operator:
`char c = mystring[2];//third char because first has offset 0`

## Solution 4

As an alternative to the 'parsing approach', you might embed in your `C` application a scripting language (see for instance Embedding a scripting language inside your C/C++ code[^] ) and let the latter to do the bulk of the work (i.e. compute the result of an expression contined in a string).