zoukankan      html  css  js  c++  java
  • C++中int转为string

    //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>
  • 相关阅读:
    关于java的scanner类
    switch_case注意事项
    MySQL数据库语句总结
    注册验证
    简单的java水果商店后台
    easyui判断下拉列表
    springmvc的前端控制器
    springmvc注解驱动
    双色球
    初来乍到
  • 原文地址:https://www.cnblogs.com/hxsyl/p/2671111.html
Copyright © 2011-2022 走看看