21xrx.com
2024-12-27 04:44:56 Friday
登录
文章检索 我的文章 写文章
C++ 如何判断输入是否为空?
2023-07-09 14:42:35 深夜i     --     --
C++ 判断 输入

在 C++ 中,判断输入是否为空有多种方法。下面节选了两种常见的方式介绍:

方法1:使用 std::cin.eof() 函数

std::cin.eof() 函数判断标准输入流是否已经结束,可以借此判断是否出现了空输入。

代码示例:


#include <iostream>

int main()

{

  std::string input;

  std::cout << "+-------------------------------------------------+" << std::endl;

  std::cout << "| Please input something, \"Ctrl+D\" to exit input. |" << std::endl;

  std::cout << "+-------------------------------------------------+" << std::endl;

  while (std::getline(std::cin, input))

  {

    if (std::cin.eof()) // 判断是否出现了空输入

    

      std::cout << "Input is empty!" << std::endl;

      break;

    

    else

    

      std::cout << "Input is: " << input << std::endl;

    

  }

  return 0;

}

执行结果1:


+-------------------------------------------------+

| Please input something, "Ctrl+D" to exit input. |

+-------------------------------------------------+

Input is: Example Line1.

Input is: Example Line2.

Input is empty!

执行结果2:


+-------------------------------------------------+

| Please input something, "Ctrl+D" to exit input. |

+-------------------------------------------------+

Input is empty!

方法2:使用 std::cin.peek() 函数

std::cin.peek() 函数获取标准输入流中下一个字符,可以借此判断是否出现了空输入。

代码示例:


#include <iostream>

int main()

{

  std::string input;

  std::cout << "+------------------------------------+" << std::endl;

  std::cout << "| Please input something, \"Enter\" to exit input. |" << std::endl;

  std::cout << "+------------------------------------+" << std::endl;

  while (std::cin.peek() != '\n' && std::cin.peek() != EOF) // 判断是否出现了空输入

  {

    std::getline(std::cin, input);

    std::cout << "Input is: " << input << std::endl;

  }

  if (std::cin.peek() == EOF)

  

    std::cout << "Input is empty!" << std::endl;

  

  return 0;

}

执行结果1:


+------------------------------------+

| Please input something, "Enter" to exit input. |

+------------------------------------+

Input is: Example Line1.

Input is: Example Line2.

执行结果2:


+------------------------------------+

| Please input something, "Enter" to exit input. |

+------------------------------------+

Input is empty!

  
  
下一篇: "Node.js 创始人"

评论区

{{item['qq_nickname']}}
()
回复
回复