我想在 C 中创建一个循环,当程序要求输入整数并且用户键入非数字字符时,程序会再次要求输入整数。
我刚刚找到了下面的代码。但我不明白这意味着什么 scanf("%*[^\n]%*c")
。 ^\n
是什么意思? ^\n
和 c
之前的 *
是什么意思?
/*
This program calculate the mean score of an user 4 individual scores,
and outputs the mean and a final grade
Input: score1, score2,score2, score3
Output: Mean, FinalGrade
*/
#include <stdio.h>
//#include <stdlib.h>
int main(void){
int userScore = 0; //Stores the scores that the user inputs
float meanValue = 0.0f; //Stores the user mean of all the notes
char testChar = 'f'; //Used to avoid that the code crashes
char grade = 'E'; //Stores the final
int i = 0; //Auxiliar used in the for statement
printf("\nWelcome to the program \n Tell me if Im clever enough! \n Designed for humans \n\n\n");
printf("Enter your 4 notes between 0 and 100 to calculate your course grade\n\n");
// Asks the 4 notes.
for ( ; i<=3 ; i++ ){
printf("Please, enter your score number %d: ", i+1);
//If the note is not valid, ask for it again
//This is tests if the user input is a valid integer.
if ( ( scanf("%d%c", &userScore, &testChar)!=2 || testChar!='\n')){
i-=1;
scanf("%*[^\n]%*c");
}else{ //Enter here if the user input is an integer
if ( userScore>=0 && userScore<=100 ){
//Add the value to the mean
meanValue += userScore;
}else{ //Enter here if the user input a non valid integer
i-=1;
//scanf("%*[^\n]%*c");
}
}
}
//Calculates the mean value of the 4 scores
meanValue = meanValue/4;
// Select your final grade according to the final mean
if (meanValue>= 90 && meanValue <=100){
grade = 'A';
} else if(meanValue>= 80 && meanValue <90){
grade = 'B';
} else if (meanValue>= 70 && meanValue <80){
grade = 'C';
} else if(meanValue>= 60 && meanValue <70){
grade = 'D';
}
printf("Your final score is: %2.2f --> %c \n\n" , meanValue, grade);
return 0;
}
最佳答案
scanf("%*[^\n]%*c") 的详 segmentation 析
:
%*[^\n]
扫描\n
之前的所有内容,但不扫描\n
中的内容。星号(*
)告诉它丢弃扫描到的所有内容。%*c
扫描单个字符,该字符将是此例中%*[^\n]
留下的\n
案件。星号指示scanf
丢弃扫描到的字符。
%[
和 %c
都是格式说明符。你可以看看他们做了什么here 。两个说明符中的星号都告诉 scanf
不要存储这些格式说明符读取的数据。
如@chux commented below ,它将清除 stdin(标准输入流)的一行,直到并包括换行符。在您的情况下,包含无效输入的行将从 stdin
中清除。
用起来比较好
scanf("%*[^\n]");
scanf("%*c");
清除stdin
。这是因为,在前一种情况(单个 scanf
)中,当要扫描的第一个字符是 \n 时,
字符和 %*[^\n]
将失败scanf
的其余格式字符串将被跳过,这意味着 %*c
将不起作用,因此 \输入中的 n
仍将位于输入流中。在这种情况下,这种情况不会发生,因为即使第一个 scanf
失败,第二个也会执行,因为它们是单独的 scanf
语句。
关于c - `scanf("%*[^\n]%*c")` 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53986554/