Home > Blockchain >  Can I place the result into an int variable using either atof or atoi?
Can I place the result into an int variable using either atof or atoi?

Time:06-27

In c: Given the following code

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

Is there a difference between?

a = atoi(word) 
a = atof(word)

CodePudding user response:

atoi returns integer type, atof returns double.

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

CodePudding user response:

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

  • Related