Need explaining

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
32
33
34
35
36
37
38
39
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

void salaryf(char *a);

int main()
{
    char salary[16];
    char pound = 156;
    
    for(;;)
      {
        cout << "Please enter the following information('q' to quit):\n\n";
        
        for(;;)
         {
            cout << "What is your current salary: " << pound;
            gets(salary);
            if(!strcmp(salary, "q")) return 0;
            else
             {
               salaryf(salary);
             }
         } 
      }
      
      cin.get();
      return 0;
}

void salaryf(char *a)
{
       *a = atof(a);
       cout<< "Current Salary: " << a << '\n';
       return;       
}


could someone compile this please and tell me why when you input a number it gives you an odd result :S

Also my compiler says:
In function 'void salaryf(char*):
[Warning] converting to 'char' form double

I thought atof() did char to double?
atof() does ASCII to float, where ASCII essentially means C-string.

The problem with your code is on the line that the compiler is complaining about.

(Hint: typecasting and typecast warnings are very often bugs in your code).

So you're saying that what i thought to be "change this char array to a double" is actually saying "change this char array to C-string"?

I'm not gonna lie i'm confused on what I can do :S
char array and C strings are the same thing, a double is a floating point number

*a = atof(a);

atof returns a double and you are assigning its data to a char (which is mush smaller than a double) so is likely that you will lose data in the conversion
It have something to do with the way i'm passing it to the function though, because this program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    char ch[8] = "123345";
    int num = 2;
    
    cout << atof(ch) + num;
    
    cin.get();
    return 0;
}


gives out the right output of 123347

and if i change my code to just on line 24 to just cout atof(salary) then it works fine. What is wrong with my function?
Last edited on
try this:
1
2
3
4
void salaryf(char *a)
{
       cout<< "Current Salary: " << atof(a) << '\n';   
}
Hmm well the right numbers are being outputted now but the "Current Salary: " isn't.
Topic archived. No new replies allowed.