atoi()函式與c_str()函式使用
阿新 • • 發佈:2018-12-21
C 語言 atoi()函式
描述
C 庫函式 int atoi(const char *str) 把引數 str 所指向的字串轉換為一個整數(型別為 int 型)。但不適用於string類串,可以使用string物件中的c_str()函式進行轉換。
宣告
int atoi(const char *str)
返回值
該函式返回轉換後的長整數,如果沒有執行有效的轉換,則返回零。
C++ c_str()函式
語法:
const char *c_str()
描述
**c_str()**函式返回一個指向正規c字串的指標,內容與string串相同。將string物件轉換為c中的字串樣式。
注意:c_str()函式返回的是一個指標,可以使用字串複製函式strcpy()
示例
#include<iostream>
#include<cstdlib>
#include<string>
#include<string.h>
using namespace std;
int main()
{
char s[5]="123";
int a = atoi(s);
cout << a << endl; //123
string ss="abcd";
char b[20];
strcpy(b,ss.c_str());
cout<< b<<endl; //abcd
return 0;
}```