• c语言中怎样用scanf()读入带空格的字符串?


    楼主

    发表于: 2011-01-14 15:39:55

    #include <stdio.h>

    int main(void)
    {
    int i;
    char a[5];

    scanf("%s", a);
    printf("%s ", a);

    return 0;

    }

    运行输入hello world
    回车
    则输出的只是空格之前的部分,怎样把空格之后的部分也输出呢?

    2楼

    回复于: 2011-01-14 17:27:23

    谁说scanf不能做到?

    #include <stdio.h>
    int main()
    {
    char str[128];
    scanf( "%[^ ]", str );
    printf( "%s ", str );
    return 0;
    }

    scanf中的正则表达式

    1、定制自己的扫描集 %[abc]、%[a-z]、%[^abc]、%[^a-z],比isdigit()、isalpha()更加灵活。[]内是匹配的字符,^表示求反集。
    int i;
    char str[80], str2[80];
    // scanf("%d%[abc]%s", &i, str, str2);
    // printf("%d %s %s ",i,str,str2);
    // scanf("%[a-zA-Z0-9]", str);
    // scanf("%[^abce]", str);
    scanf("%[^a-z]", str);
    printf("%s ",str);

    2、读入一个地址并显示内存地址的内容
    int main(void)
    {
    char ch='c';
    printf("%p ", &ch); // print the address of ch.
    char *p;
    cout<<"Enter an address: ";
    scanf("%p", &p); //input the address displayed above
    printf("Value at location %p is %c ",p,*p);
    return 0;
    }

    3、丢弃不想要的空白符:scanf("%c %c");

    4、控制字符串中的非空白符:导致scanf()读入并丢弃输入流中的一个匹配字符。"%d,%d";

    5、压缩输入:在格式码前加上*,则用户就可以告诉scanf()读这个域,但不把它赋予任何变量。
    scanf("%c%*c, &ch); 使用此方法可以在字符处理时吃掉多余的回车。


    例1:从<sip:tom@172.18.1.133>中提取tom
    const char* url = "<sip:tom@172.18.1.133>";
    char uri[10] = {0};
    sscanf(url, "%*[^:]:%[^@]", uri);
    cout << uri << endl;

    例2:从iios/12DDWDFF@122中提取 12DDWDFF
    const char* s = "iios/12DDWDFF@122";
    char buf[20];
    sscanf(s, "%*[^/]/%[^@]", buf);
    cout << buf << endl;

     

    3楼

    回复于: 2011-01-14 21:15:47

    int t[999];
    int sum=0;
    while(scanf("%c",&t[sum++])!=EOF);

     

     

     

     

  • 相关阅读:
    python3(四)list tuple
    python3(三)enc
    python3(二)
    Scala学习
    spark本地开发环境搭建及打包配置
    最常见的 Git 问题和操作清单汇总
    Idea离线安装plugins插件 如Lombok
    springboot httpsession.getAtt....is null
    idea打包报错Cleaning up unclosed ZipFile for archive D:m2commons-beanutilscommons-beanutils1.9.2...
    springboot https证书配置
  • 原文地址:https://www.cnblogs.com/huhu0013/p/3934660.html
Copyright © 2020-2023  润新知