C++中int转为string

简介: //c++中int转为string #include #include using namespace std; int main() { int i,j,k; string s(""); char *temp = new char; ...
//c++中int转为string 
#include <iostream>
#include <string>
using namespace std;

int main()
{
     int i,j,k;
     string s("");
     char *temp = new char;
     sprintf(temp,"%d",1234);
     s += string(temp);
     cout<<s<<endl;
     cout<<s[0]<<" "<<s[1]<<" "<<s[2]<<endl;
     while(1);
     return 0;
}

     

 

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main()
{
     int i,j,k;
     stringstream s;//包含在sstream头文件里 
     s<<1234;
     string ch = s.str();
     cout<<ch<<endl;
     while(1);
     return 0;
}

/*
输入输出那些事: cout.width(12);  //设置输出宽度为12       cout<<f[i];
要使 cin.get() 大法还有用,可以配对使用 cin.clear() 与 cin.sync()。
两个函数:cin.clear() 用于清除流的失败状态(如果有);而 cin.sync() 用于清空输入流。
*/

 

#include <iostream> 
using namespace std;
void main()  
{ double values[]={1.23,35.36,653.7,4358.24};
  for(int i=0; i<4; i++)
  {  cout.width(10);
     cout.fill('*');
     cout<<values[i]<<'\n';  
  }
}

输出结果:
******1.23
*****35.36
*****653.7
***4358.24

#include <iostream>  
#include <iomanip>  
using namespace std;
void main()  
{ double values[]={1.23,35.36,653.7,4358.24};
  char *names[]={"Zoot","Jimmy","Al","Stan"};
  for(int i=0;i<4;i++)
   cout<<setw(6)<<names[i]
       <<setw(10)<<values[i]
       <<endl;  
}

输出结果:
  Zoot      1.23
 Jimmy     35.36
    Al     653.7
  Stan   4358.24

两者作用是一样的,都是设定下一次输出输入宽度,但setw是操作子,而width是成员函数!
如
const char *str1 = "hello";
const char *str2 = "world";

cout.width(10);
cout<<str1;
cout.width(10);
cout<<str2<<endl;

或者使用:
cout<<setw(10)<<str1<<setw(10)<<str2<<endl;
显然使用setw要更方便,不过要包含头文件:
#include <iomanip>

 

目录
相关文章
|
15天前
|
C++ 容器
|
5天前
|
存储 安全 C++
【C++打怪之路Lv8】-- string类
【C++打怪之路Lv8】-- string类
10 1
|
15天前
|
C++ 容器
|
15天前
|
C++ 容器
|
15天前
|
存储 C++ 容器
|
19天前
|
安全 C语言 C++
【C++篇】探寻C++ STL之美:从string类的基础到高级操作的全面解析
【C++篇】探寻C++ STL之美:从string类的基础到高级操作的全面解析
31 4
|
19天前
|
存储 编译器 程序员
【C++篇】手撕 C++ string 类:从零实现到深入剖析的模拟之路
【C++篇】手撕 C++ string 类:从零实现到深入剖析的模拟之路
50 2
|
19天前
|
编译器 C语言 C++
【C++】C++ STL 探索:String的使用与理解(三)
【C++】C++ STL 探索:String的使用与理解
|
19天前
|
存储 编译器 C++
【C++】C++ STL 探索:String的使用与理解(二)
【C++】C++ STL 探索:String的使用与理解
|
19天前
|
编译器 C语言 C++
【C++】C++ STL 探索:String的使用与理解(一)
【C++】C++ STL 探索:String的使用与理解