#include<stdio.h>/* printf, fgets */#include<stdlib.h>/* atoi */int main (){int i;char buffer[256];
printf ("Enter a number: ");
fgets (buffer,256,stdin);
i = atoi (buffer);
printf ("The value entered is %d. Its double is %d.\n",i,i*2);return0;}
采用sstream头文件中定义的字符串流对象来实现转换。
itringstream is("12");//构造输入字符串流,流的内容初始化为“12”的字符串int i;
is >> i;//从is流中读入一个int整数存入i中
二、int转string
头文件 < string > 中to_string函数
#include<iostream>// std::cout#include<string>// std::string, std::to_stringint main (){
std::string pi ="pi is "+ std::to_string(3.1415926);
std::string perfect = std::to_string(1+2+4+7+14)+" is a perfect number";
std::cout << pi <<'\n';//pi is 3.141593
std::cout << perfect <<'\n';//28 is a perfect numberreturn0;}
int转C风格char* ,头文件< cstdlib >中的itoa函数 char * itoa ( int value, char * str, int base );
一、string转int头文件< string >中提供的stoi函数int stoi (const string& str, size_t* idx = 0, int base = 10);int stoi (const wstring& str, size_t* idx = 0, int base = 10);#include <iostream...