【发布时间】:2019-02-24 04:29:49
【问题描述】:
如何将双精度数据类型插入char* 数组?我试过使用std::to_string() 和c_str(),但似乎都没有成功。
基本上我正在尝试使用execvp() 调用一个c++ 程序,从读取man page 我认为它需要接收char* 数组。
我正在尝试调用该程序,然后将双精度 a, b, and c 作为 argv 参数传递给正在调用的程序 execvp()。
例如当a = 0.1, b =0.1, c = 0.1 execvp(args[0], args) 应该和终端调用一样:./RL 0.1 0.1 0.1
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <string>
int main()
{
char *args[5];
args[0] = "RL";
std::string temp;
for(double a = 0.1; a < 1; a += 0.1){
for(double b = 0.1; b < 1; b += 0.1){
for(double c = 0.1; c < 1; c+= 0.1){
temp = std::to_string(a); //attempted to convert the double to a string
args[1] = temp.c_str(); //attempted to convert the string to c string
temp = std::to_string(b);
args[2] = temp; //attempted to just insert the string
args[3] = c; //attempted to insert as double
std::cout << "Calling: " << a << " " << b << " " << c << std::endl;
execvp(args[0], args);
}
}
}
return 0;
}
我收到这样的错误:
RLdriver.cpp:14:32: error: assigning to 'char *' from incompatible type 'const
std::__1::basic_string<char, std::__1::char_traits<char>,
std::__1::allocator<char> >::value_type *' (aka 'const char *')
args[1] = temp.c_str();
~~~~~^~~~~~~
RLdriver.cpp:16:27: error: assigning to 'char *' from incompatible type
'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char>
>')
args[2] = temp;
^~~~
RLdriver.cpp:17:27: error: assigning to 'char *' from incompatible type 'double'
args[3] = c;
编辑:我知道exec() 在这种循环意义上不会真正起作用,因为它取代了当前程序,但我知道以后如何处理它,只是试图让 args 的传递起作用。
【问题讨论】:
-
我删除了 C 标签。当您需要 C++ 方面的帮助时,请不要标记 C。
-
好的,这是一个 C 函数,所以我认为这很重要,但请注意。
-
你显然是在用 C++ 编译器编译它,这对所有的 C 代码都是不可能的。