[英]What is the C++ equivalent of C language's scanf("%*c")?
客观的:
#include<stdio.h>
void main(void){
int num1, num2;
printf("Enter num1 here : ");
scanf("%d%*[^\n]%*c", &num);//First scanf statement.
printf("Enter num2 here : ");
scanf("%d", &num2);//Second scanf statement.
printf("num1 is : %d\n
num2 is : %d", num, num2);
}
/* OUTPUT */
1st number : 25 asdfasfasfasf
2nd number : 30
Input 1 : 25
Input 2 : 30
/* This will work by discarding any non */
/* In the program above I didn't write a printf statment to display the text "1st num, 2nd num". This is just so the output is a bit more clear. I am aware of it. */
现在,如果您将第一个 scanf 从scanf("%d%[^\n]%*c");
到scanf("%d");
并给出相同的输入,您将得到以下 output:
#include<stdio.h>
void main(void){
int num1, num2;
printf("Enter num1 here : ");
scanf("%d", &num1);
printf("Enter num2 here : ");
scanf("%d", &num2);
printf("num1 : %d\nnum2 : %d", num1, num2);
}
//OUTPUT//
Enter num1 here : 11 asdf
Enter num2 here : num1 : 11
num2 : 32764
/*As you might see, I am not prompted for 2nd input. Instead the already present characters in the buffer are used.*/
简报:
scanf("%d%[^\n]%*c");
将删除所有冗余字符,如空格、换行符、字母数字,这些字符在接受另一个输入之前/之后形成缓冲区的数字之后。 我怎样才能在 C++ 在我的cin >> var;
将获取缓冲区中剩余的字符,然后丢弃它们。 这仅适用于 0-9 的数字。 但我感兴趣的是*[^\n]
和*c
因为它可以帮助我从缓冲区中读取字符而不将它们保存在任何地方,这在技术上意味着它们被丢弃。排除:
cin >> ws;
cin.ignore(numeric_limits::max(),'\n');
我已经找到了上述方法,但除非没有其他更可行的选择,否则我宁愿不使用这些方法,因为它涉及包含外部库#limits
和#vector
接受。
在 C
scanf("%[^\n]%*c");
将在接受另一个输入之前/之后从缓冲区中删除所有冗余字符,如空格、换行符、alphaNumerics。
这在很多方面都是错误的。
"%[^\n]%*c"
扫描 1 个或多个非'\n'
(尝试保存它们),然后扫描 1 个'\n'
。 必须存在一个前导非'\n'
否则扫描停止。 空格和字母数字没有什么特别之处 - 只是'\n'
和非'\n'
。
未定义的行为: "%[^\n]"
缺少用于保存输入的匹配指针。 即使使用匹配的char *
,它也缺少宽度并且容易出现缓冲区溢出。 它比gets()
更糟糕。
仅输入"\n"
,不会消耗任何内容,也不会保存任何内容。 scanf("%[^\n]%*c");
如果第一个字符是'\n'
,则无法使用任何内容。 如果不检查返回值,调用代码不知道是否读取了任何内容。 匹配的char *
(如果存在)未更改或可能不确定。
不要使用scanf("%[^\n]%*c");
或其 C++ 等效std::scanf("%[^\n]%*c");
从 C++20 开始,您可能想要使用std::format 。 这基本上是在标准 C++ 中实现FMT 。
对于更复杂的场景,正则表达式应该会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.