如何让while循环中的scanf在读取到错误的数值后提醒用户重新输入

这个程序是用来测试用户所输入的值是否是一个整数,如果是整数则通过,如果不是整数则要求重新输入,但现在这段代码,在用户输入一个非整数后会持续打印“当前输入不合法”
请各位提供一个思路解决这个问题,感谢!

long check()
{
    int input;
    int test = 1;
    while (test)
    {   
        bool goout;
        goout = scanf_s("%d", &input);
        if (goout==false)
        {
            printf("当前输入不合法\n");
            bool goout;
            goout = scanf_s("%d", &input);
        }
        else
        {
            return input;
            goout = false;
            test = 0;
        }
    }
    
}//检验输入

long check()
{
    int input = 0;
    int test = 1;
    while (test)
    {   
        bool goout;
        goout = scanf_s("%d", &input);
        if (goout==false)
        {
            printf("当前输入不合法, 请重新输入\n");
            bool goout;
            continue;
        }
        else
        {
            return input;
            goout = false;
            test = 0;
        }
    }
   return input; 
}

long check()
{
    int input;
    bool goout;
    while (1)
    {   
        goout = scanf_s("%d", &input);
        if (!goout)
        {
            printf("当前输入不合法\n");
        }
        else
        {
            return input;
        }
    }
    
}//检验输入
 

你需要把非法输入从输入流中提取出来,否则非法输入一直在输入流中,就会死循环。

#include <iostream>
#include <sstream>
#include <string>

int check() {
  int input = 0;
  std::string line;
  while (std::getline(std::cin, line)) {
    std::istringstream ss(line);
    if (ss >> input)
      return input;
    else
      std::cerr << "当前输入不合法\n";
  }
  return input;
}

int main() {
  std::cout << check() << '\n';
  return 0;
}