Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can assign double to string?

Tags:

c++

According to this page, there are five ways to assign something to a string:

          string (1) string& operator= (const string& str);
        c-string (2) string& operator= (const char* s);
       character (3) string& operator= (char c);
initializer list (4) string& operator= (initializer_list<char> il);
            move (5) string& operator= (string&& str) noexcept;

Then why could I compile the text below? Which of this options was used by compiler?

#include <iostream>
#include <string>

int main()
{
  std::string s;
  double d = 1.0;
  s = d; 
  std::cout << s << std::endl; 
}

And this is not just a senseless question - I've spent long hours trying to find this s = d assignment in my code. It should have been s = std::to_string(d) of course.

Compiler: GCC 4.8.4.

like image 371
HEKTO Avatar asked Feb 10 '17 21:02

HEKTO


People also ask

Can you change a double to a String?

We can convert double to String in java using String. valueOf() and Double. toString() methods.

How do you assign a double in java?

To declare (create) a variable, you will specify the type, leave at least one space, then the name for the variable and end the line with a semicolon ( ; ). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false).

Can we store String in double?

There are three ways to convert a String to double value in Java, Double. parseDouble() method, Double. valueOf() method and by using new Double() constructor and then storing the resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time.

How do I convert a double to a String in Salesforce?

How do I convert a Double to String? From the apex documentation: Double myDouble = 12.34; String myString = String. valueOf(myDouble);


1 Answers

Your code is equivalent to this code:

#include <iostream>
#include <string>

int main()
{
  std::string s;
  double d = 1.0;
  char j = d;
  s = j; 
  std::cout << s << std::endl; 
}

So you will output a \1 followed by a line ending.

If you're using G++, specify -Wconversion to catch things like this.

f.cpp: In function ‘int main()’:
f.cpp:8:7: warning: conversion to ‘char’ from ‘double’ may alter its value [-Wfloat-conversion]
s = d;

like image 198
David Schwartz Avatar answered Oct 08 '22 21:10

David Schwartz