zoukankan      html  css  js  c++  java
  • C++的字符输入

    字符串的输入有6中方式,这六种方式各有各的特点,我这篇学习笔记是自己的经验总结,没有去探讨内存,函数库等的复杂问题,仅仅是为了实用:

    第一:cin

      cin一次接受一个字符,所以有的人会选择定义一个字符型数组,然后用cin循环进行输入,但是cin的局限性是:遇到空格就会停止接受字符;

    第二:ch1=cin.get();

      作用也是接受一个字符,然后赋值给char类型的ch1,输出ch1;

    第三:cin.get(ch2);

      作用还是接受一个字符,和第二个一样,只不过形式不同,输出ch2;

    第四:cin.get(buff1,6);

      这里是cin.get()的第二个用法,参数表里面带有3个参数,第三个参数不写就默认为‘ ’;解释一下,第一个参数是要接受字符的字符串数组Buff1,第二个是要就收的字符的个数+1后的数;

    第五:cin.getline(buff1,5,'s')

      cin.getline()与cin.get()是差不多的,就是用getline就要包含#include<string>;而且它不把结束字符输出;

    第六:getline(cin,str);

    最后一个getline(cin,str);

      解释一下参数表,cin一定要写上去,str这是获取一行后所存放的字符串名称;

     

    最后给出一段把六种情况整合在一起的代码:

    ps:我的编译器是VS2012

    
    

    字符串的输入输出
    cin
    ch1=cin.get();
    cin.get(ch2);

    
    

    cin.get(buff1,6);
    cin.getline(buff1,5,'s')
    getline(cin,str);
    */
    #include<iostream>
    #include<string>
    using namespace std;
    int main()
    {
    //这两个常数的定义可以放在main外面的
    #define N 10
    const int S=80;

    
    

    string str;
    char ch1,ch2,ch3,ch4,ch5;
    char buff1[S];
    char buff2[N][S];

    
    

    cout<<"Please input a string "<<endl;

    
    

    cin>>buff1[S];
    cout<<"By cin ";
    cout<<buff1[S]<<endl<<endl;

    
    

    ch1=cin.get();
    cout<<"By cin.get() ";
    cout<<ch1<<endl<<endl;

    
    

    cin.get(ch2);
    cout<<"By cin.get(ch2) ";
    cout<<ch2<<endl<<endl;

    
    

    cin.get(buff1,6);
    //cin.get()第二个用法,也是输入一行(同cin.getline()),也可以加上第三个参数,和getline一样,但是区别就是,不输出分隔符~
    cout<<"By cin.get(buff1,6) ";
    cout<<buff1<<endl<<endl;//要注意这个输出是输出Buff1;

    
    

    cin.getline(buff1,5,'s');//要注意与getline的区别
    //cin.getline()有三个参数:接受字符串m,接受个数5,结束字符
    cout<<"By cin.getline(buff1,5,'s')"<<endl;
    cout<<buff1<<endl<<endl;

    
    

    getline(cin,str);
    //getline()是定义在<string>中的一个函数,这里的参数表的意思是:cin是必须要有的,str就是得到字符后存放的字符串名称,等一下输出就是输出这个str
    cout<<"By getline(cin,str)"<<endl;
    cout<<str<<endl<<endl;

    system("pause");
    return 0;
    }

     
  • 相关阅读:
    装饰器的写法以及应用环境
    面向对象中super的作用
    os与sys模块的作用与常用方法
    python re模块
    python 冒泡排序,二分法
    正则表达式
    python 高阶内置函数
    python 内置函数
    python 生成器和生成器表达式
    python 函数名的应用(第一类对象),闭包,迭代器
  • 原文地址:https://www.cnblogs.com/tianjintou/p/M-Kepler.html
Copyright © 2011-2022 走看看