zoukankan      html  css  js  c++  java
  • scanf("%[^ ]", str)正则用法,strchr()用法

    一、scanf("%[^ ]", str)正则用法

    1 [^ ]表示一读入换行字符就结束读入。这个是scanf的正则用法。我们都知道scanf不能接收空格符,一接受到空格就结束读入,所以不能像gets()等函数一样接受一行字符串,但是使用%[^ ]就可以一直读入,直到碰到’ ’才结束读入
    2 那么如果scanf("%*[ ]")表示该输入项读入后不赋予任何变量,即scanf("%*[^ ]")表示跳过一行字符串。

    #include<iostream>
    using namespace std;
    {
        char str1[1000] = {0};
        char str2[1000] = {0};
        char str3[1000] = {0};
        char str4[1000] = {0};
        scanf("%[^
    ]", str1);    // 过程1
        scanf("%[^#]", str2);     // 过程2
        scanf("%*[^
    ]", str3);   // 过程3 加了个*
        scanf("%*[^#]", str4);    // 过程4 加了个*
        cout << str1 << str2 << str3 << str4 << endl;
    }

    输入:

    You are my friend
    Are you sure?
    # 
    Are you ok?
    Can you speak English?
    No, I can't. #

    输出:

    you are my friend
    Are you sure?
    

    过程1:读到You are my friend(回车)末尾的’ ’时,结束,str1字符串为"You are my friend",
    注意: ' ’确实也还在缓冲区,不过后续都是直接从缓冲区读取字符串而不是读取字符,所以会直接跳过(tab, 空格, ‘ ’)这类空白字符。
    过程2:读到Are you sure? # 末尾的 ‘#’ 时,结束,像上面一样 ‘ ’ 也还在缓冲区,str2字符串为"Are you sure? "
    过程3:读入字符串一直到"Are you ok?"的末尾’ ’,但是并不存储这个字符串,也不存储’ ’
    过程4:读入两行,合整为字符串"Can you speak English?‘No, I can’t. "读到后面的’#’,结束,当然也是不存储’#’

    注意:有人喜欢写scanf("%[^ ]%*c", str),目的是可以把’ ’吸收掉,防止影响后续输入

    特意查了下scanf(),getchar(),getche(),getch()这些函数缓冲区角度的解释:https://www.cnblogs.com/yhjoker/p/7530837.html

    二、strchr用法

    这是C的库函数
    原型:char *strchr(const char *str, int c)
    作用:在参数 str 所指向的字符串中搜索第一次出现字符 c(一个无符号字符)的位置。
    下面是示例代码:

    #include<iostream>
    #include<cstring>
    using namespace std;
    int main()
    {
       char str[] = "I love you.cn";
       char ch = '.';
       char *point;
    
       point = strchr(str, ch);
       
       printf("|%c| 之后的字符串是 - |%s|
    ", ch, point);
    }

    输出结果:

    |.| 之后的字符串是 - |.cn|

    有人不清楚为啥输出的是 ‘.’ 后面的字符串,请想想printf("%s", str)的原理。
    另外,如果没有找到ch这个字符的话(例子里面是’.’),就返回NULL。

    原文链接:https://blog.csdn.net/weixin_43469047/article/details/83753526

  • 相关阅读:
    【转】字典转模型需要注意的问题,以及第三方框架来处理字典转模型
    【转】使用SOAP访问Web服务
    Foundation框架2
    Foundation框架1
    什么是Protocol
    什么是Block
    什么么是Category
    ARC
    autorelease简介
    循环retain
  • 原文地址:https://www.cnblogs.com/YFEYI/p/12870617.html
Copyright © 2011-2022 走看看