简体   繁体   English

将Char转换为Double C ++

[英]Convert Char to Double C++

UPDATE: I am passing a string variable and am iterating through the string character by character. 更新:我正在传递一个字符串变量,并逐个字符地遍历字符串。 Whenever I run into a decimal, I want to combine the previous position on the string (ie 2) and the next position in the string (ie 5) into a double. 每当我遇到小数时,我都想将字符串的前一个位置(即2)和字符串的下一个位置(即5)合并为一个双精度数。 So how would I go about making the char 2, char . 那么我将如何制作char 2,char。 , char 5 into one whole double value (2.5)? ,将char 5变成一个整数double值(2.5)? Without using STL classes or Vectors. 不使用STL类或向量。 What I went ahead and tried was the following below. 我继续尝试以下内容。 However, whenever I do the stuff in the var line, it doesn't hold the value 2.5 as a string. 但是,每当我在var行中进行处理时,它都不会将值2.5保留为字符串。 It holds a: "•". 它包含一个:“•”。 Is there something wrong that I am doing? 我在做错什么吗?

If your point is to parse strings to doubles, I would take a different approach to iterate through the string. 如果您的意思是将字符串解析为双精度,那么我将采用另一种方法来遍历字符串。 First, I would create an iterator splited by space to avoid checking if there is a '.'. 首先,我将创建一个按空间分割的迭代器,以避免检查是否存在“。”。 And then I would iterate through this new iterator. 然后,我将遍历这个新的迭代器。 Something like this 像这样

#include <iostream>
#include <string>
#include <sstream>
#include <iterator>
#include <vector>


int main() {
    using namespace std;
    double num;
    string variableName = "4 5 7 2.5";
    istringstream iss(variableName);
    vector<string> nums{istream_iterator<string>{iss},
        istream_iterator<string>{}};
    for (int i = 0; i < nums.size(); i++) {
        num = stod(nums[i]);
    }
    return 0;
}

The advantage of this approach is that it works regardless on how many characters are before and after the decimal point. 这种方法的优点是,不管小数点之前和之后有多少个字符,它都能起作用。

I would do something like this: 我会做这样的事情:

double x;
std::string temp = "";
std::string variableName = "4 5 7 2.5";
std::string::size_type sz;     // alias of size_t
for (int i = 0; i < variableName.length(); i++) // iterates through variableName
{
    if (variableName[i] == '.') {
        temp += variableName[i - 1];
        temp += variableName[i];
        temp += variableName[i + 1];
        x = stod(temp, &sz);
    }
}
return x;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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