gpt4 book ai didi

c - `scanf("%*[^\n]%*c")` 是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 17:05:12 24 4
gpt4 key购买 nike

我想在 C 中创建一个循环,当程序要求输入一个整数并且用户键入一个非数字字符时,程序再次要求输入一个整数。

我刚找到下面的代码。但我不明白这是什么意思 scanf("%*[^\n]%*c")^\n 是什么意思? ^\nc 之前的* 是什么意思?

/*

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") 分解:

  • %*[^\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/30065675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com