C语言scanf函数

C语言常见问题

在学习C语言的时候,我们常常从终端输入一个数字、字符、字符串等。
那么我们就会用到scanf()一类的函数。
但是我们从终端输入的字符串数据和我们在程序代码中给定的字符串是有区别的

我们都知道,C语言的字符串我们存储在字符数组里面,并且是以’\0’结尾。我们在许多涉及到字符串的函数也都是以这个判断的。

#include <stdio.h>
//char *s ----字符串的地址
//brief---统计这个字符串有多少字符/字符串的长度。
//while 的条件是 s[n] != '\0' 的时候如果输入的字符串有空格,就不统计 ;下面是运行。
int length(char *s)
{
    int n = 0;
    while (s[n] != '\0') {
    	n++;  
    }
    return n;
}

int main() {
    char str[50] = {0};
    int len = 0;

    printf("please input a string you want:\n\n");
    scanf("%s", str);
 
    len = length(str);
    printf("\nThere are %d characters in the string.\n\n", len);

   return 0;
}

运行结果:
please input a string you want:
4756jh lbh
There are 6 characters in the string. */

也就是说我明明用‘\0’作为结束判断,但是却只是以我输入的空格前面的统计。
我的猜测:

1、在终端输入我没有加结束标志。(这种可能较小)。代码很简单。应该不会多次用局部内存。返回也不是这样的错误结果。
等等。。。我尝试很多。
2、将字符串在代码中给好--------没用错误。和我预想的一样。
3、在判断条件上。。。

但是最终的原因是scanf()函数。
$man scanf

函数原型;
int scanf(const char *restrict format, …);
这是其中一段描述。

The scanf() family of functions scans input according to a format, as described below. This format may
contain conversion specifiers; the results from such conversions, if any, are stored through the
pointer arguments. The scanf() function reads input from the standard input stream stdin, fscanf()
reads input from the stream pointer stream, and sscanf() reads its input from the character string
pointed to by s.

这是%s的描述
white space-------这个指的应该不仅仅是空格,而是空格、tab、回车。
除了回车键没有测试,剩下两个都测试了。

如何从终端输入空格、回车、tab等字符?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值