scanf("%[^n],c)和scanf("%[^ ],c)具体含义

【扩展知识1】scanf("%[^n],c)和scanf("%[^ ],c)具体含义

     以前自己也遇到这些问题,也查了查,但慢慢的又忘了~- ~。今天又碰到,所以就把它写成篇文章吧,以供大家查阅。本文中写的内容有参考网上高手们的,我只是总结总结,谢谢。   


#include <stdio.h>

 

int main( void )

{

         chararray[ 100 ];

        

         printf("输入您要打印的内容:" );

         scanf("%[^ ]", array ); 

        

         printf("您输入的内容为:%s\n", array );

          

         return0;

}

#include <stdio.h>

 

int main( void )

{

	char array[ 100 ];

	

	printf("输入要打印的内容: " );

	scanf( "%s", array );  

	

	printf( "您输入的内容为: %s\n", array );

	 

	return 0;

}

解读:第一个程序使用的scanf(“%[^ ]”, array)是读入字符串直到遇到空格结束。第二个程序使用的是scanf(“%s”, array);也是遇到空格就结束。

比如输入:abcdefg abcdefg abcdefg

输出结果:abcdefg


#include <stdio.h>

 

int main( void )

{

         chararray[ 100 ];

        

         printf("输入要打印的内容:" );

         scanf("%[^\n]", array ); 

        

         printf("您输入的内容为: %s\n", array );

          

         return0;

}

解读:本程序读取字符直到遇到’\n’或回车为止。
比如输入:abcdefg abcdefg abcedef
输出结果:abcdefg abcdefg abcedef
PS:输出字符串中有\n不是换行符,只能作为字符串中的一部分处理。
比如输入:abcdefg\n abcdefg abcdefg
输出结果:abcdefg\n abcdefg abcdefg

还有一种在前面加一个*的,scanf("%*[\n]")表示该输入项读入后不赋予任何变量,即scanf("%*[^\n]")表示跳过一行字符串。

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


输入

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

输出

you are my friend
Are you sure?\n

过程1:读到You are my friend(回车)末尾的’\n’时,结束,str1字符串为"You are my friend",
注意: '\n’确实也还在缓冲区,不过后续都是直接从缓冲区读取字符串而不是读取字符,所以会直接跳过(tab, 空格, ‘\n’)这类空白字符。
过程2:读到Are you sure?\n# 末尾的 ‘#’ 时,结束,像上面一样 ‘\n’ 也还在缓冲区,str2字符串为"Are you sure?\n"
过程3:读入字符串一直到"Are you ok?"的末尾’\n’,但是并不存储这个字符串,也不存储’\n’
过程4:读入两行,合整为字符串"Can you speak English?‘No, I can’t. "读到后面的’#’,结束,当然也是不存储’#’
注意:有人喜欢写scanf("%[^\n]%*c", str),目的是可以把’\n’吸收掉,防止影响后续输入

特意查了下scanf(),getchar(),getche(),getch()这些函数缓冲区角度的解释:
写的真的好,解决了我一年的懵懵懂懂:
https://www.cnblogs.com/yhjoker/p/7530837.html


总结:
综合上述,我们可以知道%[^\n]和%[^ ]的含义了。符号^ 表示取反的意思。[^ ]表示除了空格,所有的字符都可以读取;[^\n]则表示除了换行符,所有的字符都可以读取。
有时候,在程序中需要读取字符串直到回车为止,也可以使用函数gets(array)读取。


转载于http://oursharingclub.joinbbs.net和 codingit.howbbs.comA 

发布了37 篇原创文章 · 获赞 3 · 访问量 2397

猜你喜欢

转载自blog.csdn.net/Stillboring/article/details/104356244