简体   繁体   中英

conversion from empty string to float using stringstream results in non-zero value

I have tried to solve this with previously answered questions like Conversion from string to float changes the number but I have not been successful.

In my code I take a string full of ' ' characters and convert it to float using stringstream. It worked fine (returned me a zero valued float) until I performed another conversion right after that. When a conversion is executed afterwards, the value stored in the float previously converted is not zero, but 4.57048e-41. I hope the following code explains my problem more clearly.

I started with:

std::stringstream ss;
float a;
float b;
for(int i=0; i<LIM; ++i){
    //some other conversions using same stringstream
    //clearing stringstream    
    ss.str( std::string() );
    ss.clear();

    ss << str1;    //string full of empty spaces, length of 5
    ss >> a;
    std::cout << a;//prints zero
}

That worked just fine, but when I changed it to

std::stringstream ss;
float a;
float b;
for(int i=0; i<LIM; ++i){
    //some other conversions using same stringstream
    //clearing stringstream    
    ss.str( std::string() );
    ss.clear();

    ss << str1;    //string full of empty spaces, length of 5
    ss >> a;
    std::cout << a;//prints 4.57048e-41

    ss.str ( std::string() );
    ss.clear();

    ss << str2;    //another string full of empty spaces, length of 5
    ss >> b;
    std::cout << b;//prints zero
}

I am using gcc 4.6.3 with the following flags: -o2 -Wall -Wextra -ansi -pedantic

Any kind of help will be greatly appreciated, but I am not willing to use doubles.

Many thanks!

If the conversion fails, then the target value isn't changed. In your case, it still has its original uninitialised value; so printing it gives garbage or other undefined behaviour.

You should check whether the conversion succeeded:

if (!(ss >> a)) {
    a = 0; // or handle the failure
}

or use conversion functions like std::stof in C++11, or boost::lexical_cast , which throw to indicate conversion failure. (Or, as mentioned in the comments, just set it to zero to start with if you don't otherwise need to detect failure).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM