简体   繁体   中英

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. So how would I go about making the char 2, char . , char 5 into one whole double value (2.5)? Without using STL classes or Vectors. 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. 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;

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