-1

In c: Given the following code

int a;
char word[]=<some string>

Is there a difference between?

a = atoi(word) 
a = atof(word)
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Niv
  • 850
  • 1
  • 7
  • 22

2 Answers2

2

atoi returns integer type, atof returns double.

So in the atof scenario you are additionally converting the temporary double into your int

The Dreams Wind
  • 8,416
  • 2
  • 19
  • 49
  • Thank you. But does the conversion make a difference in the end point? I mean other than the fact that there's a conversion, is there a difference between the two scenarios? – Niv Jun 27 '22 at 06:29
  • @Niv Given that this already is rather different, what would you consider to be a difference? – Gerhardh Jun 27 '22 at 07:22
0

Yes, you can.

But the compiler will emit warnings. See below:

enter image description here

It tells you what will happen.

All double or float values will be truncated (not rounded).

See the below code:

#include <iostream>
#include <cstdlib>

int main() {
 
    int i1{};
    int i2{};
    int i3{};
    char s1[] = "42";
    char s2[] = "42.1";
    char s3[] = "42.9";

    i1 = std::atof(s1);
    i2 = std::atof(s2);
    i3 = std::atof(s3);

    std::cout << s1 << "\t--> " << i1 << '\n'
        << s2 << "\t--> " << i2 << '\n'
        << s3 << "\t--> " << i3 << '\n';
}

If you want to get rid of the warnings and be more clean, you need to add a cast statement. Like below:

#include <iostream>
#include <cstdlib>

int main() {

    int i1{};
    int i2{};
    int i3{};
    char s1[] = "42";
    char s2[] = "42.1";
    char s3[] = "42.9";

    i1 = static_cast<int>(std::atof(s1));
    i2 = static_cast<int>(std::atof(s2));
    i3 = static_cast<int>(std::atof(s3));

    std::cout << s1 << "\t--> " << i1 << '\n'
        << s2 << "\t--> " << i2 << '\n'
        << s3 << "\t--> " << i3 << '\n';
}

There will be no compiler warning:

enter image description here

Program output will be:

enter image description here

A M
  • 14,694
  • 5
  • 19
  • 44