zoukankan      html  css  js  c++  java
  • [原创]cin、cin.get()、cin.getline()、getline()、gets()、getchar()的区别

    这几个输入函数经常搞不清具体特点和用法,这里稍作总结

    一、cin>>

    1、最基本用法,输入一个变量值

    2、输入字符串,遇“空格”、“TAB”、“回车”结束,比如输入“hello world”,输出“hello”

    二、cin.get()

    1.用来接收字符,比如

    char c;

    c=cin.get();//或者cin.get(c);

    cout<<c;

    输入 hello,输出h;

    2.cin.get(字符数组名,接收字符数目)用来接收一行字符串,可以接收空格,例如

    char a[12]; 
    cin.get(a,12); 
    cout<<a<<endl; 

    输入hello world;输出hello world;

    输入hello world!!!;输出hello world(因为包含终结符号)

    三、cin.getline()

    1.cin.getline(字符数组名,接收字符数目),和cin.get()第二个用法类似,但是看编译器cin.getline()是有三个参数,默认是' ',如果将以上例子写成cin.getline(a,12,'l'),将输出he

    2.用于二维数组

    char a[2][20]; 
    for(int i=0;i<2;i++) 

    cin.getline(m[i],20); 
    }

    for(int j=0;j<3;j++) 
    cout<<"m[j]<<endl;

    四、getline(),接收字符串,可以包含空格,但是必须#include<string>

    string str; 
    getline(cin,str); 
    cout<<str<<endl; 

    五、gets(),接收字符串,可以包含空格,但是必须#include<string>

    char a[12]; 
    gets(a); 

    六、getchar(),接收一个字符,必须#include<string>

    char ch;
    ch=getchar();   //不能写成getchar(ch);

  • 相关阅读:
    01.html5+phonegap跨平台移动应用开发
    10个CSS简写/优化技巧
    JS高级学习历程-17
    JS高级学习历程-16
    算法详解之Tarjan
    分层图详解
    洛谷 题解 P1196 【[NOI2002]银河英雄传说】
    洛谷 题解 P1220 【关路灯 】
    洛谷 题解 P1352 【没有上司的舞会】
    二维前缀和详解
  • 原文地址:https://www.cnblogs.com/librasun/p/5401261.html
Copyright © 2011-2022 走看看