在C ++中将字符串解析为double和string

时间:2016-01-12 08:19:14

标签: parsing c++11 stringstream

我有一个像这样的字符串

string myStr("123ab")

我想将其解析为

double d;
string str;

d=123str=ab

我尝试使用像这样的字符串流

istringstream ss(myStr);
ss >> d >> str;

但它没有用。怎么了?

3 个答案:

答案 0 :(得分:3)

OP中的代码按预期工作:

#include <iostream>
#include <sstream>
#include <string>

int main(int argc, char** argv) {
    for (int i = 1; i < argc; ++i) {
        std::istringstream ss(argv[i]);
        double d;
        std::string s;
        if (ss >> d >> s)
            std::cout << "In '" << argv[i]
                      << "', double is " << d
                      << " and string is '" << s << "'\n";
        else
            std::cout << "In '" << argv[i]
                      << "', conversion failed.\n";
    }
    return 0;
}
$ ./a.out 123ab
In '123ab', double is 123 and string is 'ab'

Live on coliru。)

但是,它在输入123eb上失败,因为e被解释为指数指示符,并且没有后续指数。对std::istringstream这个问题没有简单的解决方法,它有点像sscanf;后备是不可能的。但是,std::strtod应找到最长的有效浮点数,因此能够处理123eb。例如:

#include <iostream>
#include <sstream>
#include <string>
#include <cstring>

int main(int argc, char** argv) {
    for (int i = 1; i < argc; ++i) {
        char* nptr;
        double d = strtod(argv[i], &nptr);
        if (nptr != argv[i]) {
            std::string s;
            if (std::istringstream(nptr) >> s) {
                std::cout << "In '" << argv[i]
                          << "', double is " << d
                          << " and string is '" << s << "'\n";
                continue;
            }
        }
        std::cout << "In '" << argv[i]
                  << "', conversion failed.\n";
    }
    return 0;
}

Live on coliru。)

答案 1 :(得分:1)

对于好的strtod来说,这似乎是一个问题。

char* end;
double d = strtod(string.c_str(), &end);
然后

end将指向应构成char*的{​​{1}}数组的开头;

str
然后

将相关内容复制到str = end; /*uses string& operator= (const char*)*/ 。由于它需要一个价值副本,因此不必担心str无效。

(请注意,如果c_str()不包含前导数字部分,则string将设置为零。

答案 2 :(得分:0)

字符串编号;     double an_number;

spark-env.sh (on Master):
  SPARK_EXECUTOR_CORES=10 (-> use 10 of the 12 Cores for executors -> the other 2 are planned for the Driver process)
  SPARK_EXECUTOR_MEMORY=60g (-> set only 60g, because the setting spark.executor.memory sets the memory also to this size, set here more memory would be a waste of the resource!)

spark-defaults.conf (on Master)
  (spark.executor.memory set as written above (=60g))
  spark.driver.cores 2 (-> use the 2 cores, which aren't use for executors yet)
  spark.driver.memory 10g (can be up to ~60g, as there are only used 60 of 128 GB for the executors)

ANS:

number="9994324.34324324343242";
an_number=atof(number.c_str());
cout<<"string: "<<number<<endl;
cout<<"double: "<<an_number;
cin.ignore();