CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Hybrid View

  1. #1
    Join Date
    Mar 2013
    Posts
    31

    Needs some clarification about string to double conversion

    Hello,
    I have the following piece of code:


    string ss = findNodeValue( str, "Horizon");
    cout << "ss is: " << ss << endl;
    double dd = atof( ss.c_str());
    cout << "dd is: " << dd << endl;

    When the value of 'ss' is printed, I find it prints 1.0, but when the value of 'dd' is printed, it prints 1 whereas it is supposed to print 1.0. Could any one help me figure out what the problem is.

    Thanks in advance.

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Needs some clarification about string to double conversion

    Quote Originally Posted by jenny_wui View Post
    Hello,
    I have the following piece of code:
    1) What is "findNodeValue"? Isn't that some important information you're leaving out?

    2) ss is a std::string type -- it is not a double.

    3) dd is a double not a string.
    but when the value of 'dd' is printed, it prints 1 whereas it is supposed to print 1.0.
    No. It "prints" according to how operator << handles doubles.

    Regards,

    Paul McKenzie

  3. #3
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: Needs some clarification about string to double conversion

    If you want it to print as 1.0 then you will need to use io manipulators. The following
    Code:
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main()
    {
    double dd = 1;
    
    	cout << dd << endl;
    	cout << fixed << setprecision(1) << dd << endl;
    	return 0;
    }
    displays
    Code:
    1
    1.0
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured