将字符串转换为double型值

Filed Under (c++) by boymg on 26-03-2008

函数名: strtod
功 能: 将字符串转换为double型值
用 法: double strtod(char *str, char **endptr);
程序例:

  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3.  
  4. int main(void) 
  5. { 
  6.    char input[80], *endptr
  7.    double value
  8.  
  9.    printf("Enter a floating point number:")
  10.    gets(input)
  11.    value = strtod(input, &endptr)
  12.    printf("The string is %s the number is %lf\n", input, value)
  13.    return 0;

Code: ( cpp )

  1. #include <string>
  2. #include <iostream>
  3. #include <sstream>
  4.  
  5. using namespace std;
  6.  
  7. /* console cpp file */
  8. int main()
  9. {
  10.     char data [] = "1234.5";
  11.     double result;
  12.  
  13.     stringstream converter(data);
  14.  
  15.     converter >> result;
  16.  
  17.     cout << result << endl;
  18.  
  19.     return 0;
  20. }

Post a comment

You must be logged in to post a comment.