Floating value from character array

How to exract a floating value from a character array in separate variables .
Example : multiply 7.5 with 2
Out put : 7.5 , 2
Last edited on
Use strtok to break the input string into words/token.
Then try to use atof() function to each word, if it returns non-zero then its a valid number so print it.

Please see below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>

using namespace std;

int main() {
   string str;
   char *token = NULL;
   bool first = true;

   cout << "Enter a string: ";
   getline(cin, str);

   token = strtok((char *)str.c_str(), " \t\f\r\n");
   while (token) {
       double num = atof(token);
       // print if num is not 0 or num is 0 but token is "0"
       if ((num != 0) || ((num == 0) && (!strcmp(token, "0")))) {
            if (first == false) {
                cout << ",";
            }
            cout << num;
            first = false;
       }
       token = strtok(NULL, " \t\f\r\n");
   }
   return 0;
}
Last edited on
Topic archived. No new replies allowed.