zoukankan      html  css  js  c++  java
  • getchar(),gets(),scanf()的差异比较

    scanf( )函数和gets( )函数都可用于输入字符串,但在功能上有区别。若想从键盘上输入字符串"hi hello",则应该使用gets()函数。

    gets可以接收空格;而scanf遇到空格、回车和Tab键都会认为输入结束,所有它不能接收空格。

     

    char string[15]; gets(string); /*遇到回车认为输入结束,并且回车键用‘’代替*/

    scanf("%s",string); /*遇到空格认为输入结束*/

    所以在输入的字符串中包含空格时,应该使用gets输入。

    scanf和gets获取字符串时的区别

    1.不同点:

    scanf不能接受空格、制表符Tab、回车等;

    而gets能够接受空格、制表符Tab和回车等;

    2.相同点:

    字符串接受结束后自动加''。

    例1:

    #include <stdio.h>

    main()

    {

    char ch1[10],ch2[10];

    scanf("%s",ch1);

    //gets(ch2);

    }

    依次键入asd空格fg回车,asd空格fg回车,则ch1="asd",ch2="asd fg"。

    例2:

    #include <stdio.h>

    main()

    {

    char ch1[10],ch2[10],c1,c2;

    scanf("%s",ch1);

    c1=getchar();

    gets(ch2);

    c2=getchar();

    }

    依次键入asdfg回车,asdfg回车,则ch1="asdfg",c1=' ',ch2="asdfg",c2需输入。

    scanf :当遇到回车,空格和tab键会自动在字符串后面添加'',但是回车,空格和tab键仍会留在输入的缓冲区中。

    gets:可接受回车键之前输入的所有字符,并用' '替代 ''.回车键不会留在输入缓冲区中

    gets()用到读取字符串,用回车结束输入 

    scanf()可以读取所有类型的变量

    选择了远方,便只顾风雨兼程
  • 相关阅读:
    [LeetCode] Range Sum Query
    [LeetCode] Longest Increasing Subsequence
    [LeetCode] Bulls and Cows
    [LeetCode] Serialize and Deserialize Binary Tree
    [LeetCode] Find Median from Data Stream
    [LeetCode] Convert Sorted List to Binary Search Tree
    [LeetCode] Nim Game
    [LeetCode] Word Pattern
    安装配置说明与注意
    java.lang.OutOfMemoryError: PermGen space及其解决方法
  • 原文地址:https://www.cnblogs.com/ly-rabbit-wust/p/5575629.html
Copyright © 2011-2022 走看看