什么`scanf(“%* %* c”)`是什么意思?

我想在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  //#include  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=0 && userScore= 90 && meanValue = 80 && meanValue = 70 && meanValue = 60 && meanValue  %c \n\n" , meanValue, grade); return 0; } 

scanf("%*[^\n]%*c")细分scanf("%*[^\n]%*c")

  • %*[^\n]扫描所有内容直到\n ,但不扫描\n 。 星号( * )告诉它放弃扫描的内容。
  • %*c扫描单个字符,在这种情况下,它将是\n %*[^\n]剩余的%*[^\n] 。 星号指示scanf丢弃扫描的字符。

%[%c都是格式说明符。 你可以看到他们在这里做了什么。 两个说明符中的星号都告诉scanf ,而不是存储这些格式说明符读取的数据。

在您的情况下,此scanf在用户输入无效输入时清除stdin


最好使用

 scanf("%*[^\n]"); scanf("%*c"); 

清除stdin 。 这是因为,在前一种情况下(单扫描),当要扫描的第一个字符是\n字符时, %*[^\n]将失败,并且将跳过scanf的其余格式字符串,这意味着%*c将不起作用,因此输入中的\n仍将位于输入流中。 在这种情况下,即使第一次scanf失败,第二次scanf失败也不会发生,因为它们是单独的scanf语句。

您可以使用scanf(“%s”, s)将字符串作为C输入。 但是,它只接受字符串,直到找到第一个空格。

为了输入一行,你可以使用scanf("%[^\n]%*c", s); 其中s定义为char s[MAX_LEN] ,其中MAX_LENs的最大大小。 这里, []是扫描集字符。 ^\n表示接受输入,直到没有遇到换行符。 然后,使用此%*c ,它将读取换行符,此处使用的*表示将丢弃此换行符。