C/C++输入

C/C++输入

scanf

  • scanf("%d", &val),需要传入地址,输入换行可以结束输入,它的分隔符是空格、tab或者换行,

    #include<iostream>
    #include <string>
    #include <stdio.h>
    using namespace std;
    
    void scanf_test()
    {
        char s[10];
        scanf("%s", &s);
        cout << s << endl;
    }
    
    int main()
    {
        scanf_test();
        return 0;
    }
    

上面的程序中,如果输入的字符串中间有空格,则会直接截断,只读取前面的部分,结果如下图

这里写图片描述

getchar读取字符

  • getchar读取所有输入的字符,不会跳过空格等特殊字符

    void getchar_test()
    {
        char a[6];
        for(int i=0;i<5;i++)
        {
            a[i] = getchar();
        }
    
        a[5] = '\0';
        cout << a << endl;
    }
    

结果如下图
这里写图片描述

cin

  • cin也是按照空格、tab或者换行来分割输入的
  • 如果希望输入的字符串中能够包括空格的话,需要使用get或者getline,指定输入字符串的最大长度
  • 注意:使用get,在输入的字符串长度超过设定值时,会将剩余的部分放在缓冲区里,用于下次读取,不会报出异常;使用getline时,输入的字符串长度超过设定值时,cin会报出异常并直接退出读取,但是上一次读取的内容仍然在

  • 参考链接:http://www.cnblogs.com/A-Song/archive/2012/01/29/2331204.html

  • 代码

    void cin_test()
    {
        cout << "cin.get test" << endl;
        char s4[10];
        char s5[10];
        cin.get( s4, 10 );
        cin.get( s5, 10 );  
        cout << s4 << endl;
        cout << s5 << endl;
    
    
        cout << "cin test" << endl;
        string s1, s2;
        cin >> s1 >> s2;
        cout << s1 << endl;
        cout << s2 << endl;
    
    
        cout << "cin.getline test" << endl;
        char s[10];
        char s3[10];
        cin.getline( s, 10 );
        cin.getline(s3, 10);
        cout << s << endl;
        cout << s3 << endl;
    
    }
    

上面代码段的运行结果为
这里写图片描述

文本输入

  • 如果输入内容是存在文本文件中,则可以读取文件,对于一个内容为

    5
    A + - + -
    - + - - +
    - + + + -
    + - + - +
    B + - + -
    

    的文本文件,使用下面的方法读取,可以实现文本信息提取。

    #include <stdio.h>
    #include <string.h>
    int n;
    char map[100][100];
    int main()
    {
        freopen("in.txt", "r", stdin);
        scanf("%d", &n);
        getchar();
        for (int i = 0; i<n; i++) {
            for (int j = 0; j <n; j++) {
                scanf("%c", &map[i][j]);
                getchar();
            }
        }
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<=n;j++)
                printf("%c", map[i][j]);
            printf("\n");
        }
        return 0;
    }
    

    注意:文本中,每两个字符之间有空格,否则在scanf读取的时候会有信息丢失的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

littletomatodonkey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值