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 (i.e. 2) and the next position in the string (i.e. 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?
Asked
Active
Viewed 975 times
-1
-
[`std::stod`](http://en.cppreference.com/w/cpp/string/basic_string/stof). – Some programmer dude Mar 22 '18 at 04:48
-
2You could also look into [`std::istringstream`](http://en.cppreference.com/w/cpp/io/basic_istringstream) and using formatted input. – Some programmer dude Mar 22 '18 at 04:49
-
Parse you string using space as a delimiter, then use std::stod as mentioned by @Someprogrammerdude – Rann Lifshitz Mar 22 '18 at 04:49
-
How would you implement `std::stod` in this situation? @Someprogrammerdude – Alakd Mar 22 '18 at 04:50
-
Lastly, `std::double`? – Some programmer dude Mar 22 '18 at 04:50
-
Start by writing a function "extract word under index", which takes string and index, and returns string containing the word under it. Rest should be trivial. – hyde Mar 22 '18 at 04:57
-
@Alakd You don't implement it, you call it – David Heffernan Mar 22 '18 at 06:31
2 Answers
2
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.

Misael Alarcon
- 161
- 10
0
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;

daniel_sweetser
- 381
- 1
- 8
-
Going over your suggestion, wouldn't it crash as it reaches x? I attempted and debugged it, and it tells me "invalid stod argument". – Alakd Mar 22 '18 at 05:09
-
You are correct- I've adjusted the code to resolve the exception. – daniel_sweetser Mar 22 '18 at 06:21