【发布时间】:2017-08-02 05:56:16
【问题描述】:
我是 C++ 新手,不过我已经用 C 编程了一段时间。 尝试读入一个字符串,然后使用 strtol 将字符串转换为 int。 我正在使用 gcc 编译器。 我收到以下错误消息:“c++ error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string}' to 'const char*' for argument '1' to 'long int strtol( const char*, char**, int)' int c = strtol(str[j], &p, 10);". 我尝试了不同类型的转换,但我非常喜欢 strtol 以供将来参考。我的向量字符串有什么关系吗?
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
using std::string;
int main()
{
int a = 0;
int i = 0;
int size = 0;
int* big;
cin>>a;
size = a*2;
int sizes[size];
string *str = new string[size];
while(i < a){
cin>>str[i];
i++;
}
i = 0;
while(i < a){
cout << str[i] << endl; // just for checking
i++;
}
for (int j =0; j<size-1;j++){
char* p;
char* q;
int c = strtol(str[j], &p, 10);
if (!*p) {
sizes[j] = *p;
}else{
sizes[j] = *p/2;
}
}
return 0;
}
提前致谢!
【问题讨论】:
-
你能把代码减少到导致错误的原因吗?或者至少提到它是哪一行?
-
int sizes[size];不是标准 C++,这是一个扩展,这意味着此代码不可移植。当您还拥有using namespace std;时,using std::string;也是多余的。你也永远不会删除string *str = new string[size];(你应该这样做,尽管更好的解决方案是std::vector)