C++ atoi 怎么用

来源:百度知道 编辑:UC知道 时间:2024/06/20 15:29:03
我用VC++6.0 编高精度加法 想将200位长的字符串或字符数组转换到一个200位长的int数组里 用atoi吗 不会用这个函数 怎么用?
string achar;
getline(cin, achar);
int a[200];
int l, j;
l = achar.length();
for (j = 0; j < l; j++)
{
a[j] = atoi(achar.substr(j, 1));
}
此为部分程序,无法编译

error C2664: 'atoi' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'const char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

这是错误信息

哪位高手指导一下 谢啦

string的成员substr返回的是string类型的对象,而atoi函数要求参数为char*型字符串,所以可以使用string的c_str成员函数,对程序作如下修改即可:

a[j] = atoi( achar.substr(j, 1).c_str() );

a[j] = atoi(achar.substr(j, 1)).c_str();

const char* c_str ( ) const;

Get C string equivalent

Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.

A terminating null character is automatically appended.

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only granted to remain unchanged until the next call to a non-constant member function of the string object.

Parameters
none

Return Value
Pointer to an internal array containing the c-string equivalent to the string content.