【问题标题】:How to check when a user presses the enter key without providing a value in C++如何检查用户何时按下回车键而不在 C++ 中提供值
【发布时间】:2026-01-07 00:55:02
【问题描述】:

在我的代码中,我想检查未输入输入值时是否按下了输入键。因为,通常按下回车键只会换行,直到没有输入输入,并且;相反,我希望它通过检测在这种情况下按下回车键来发出命令。

   #include <iostream>
   #include <string>
   using namespace std;

   int main(){    
        String str="";
        while(str!="exit"){
          cin>>str;
          if(input is not entered and enter key is pressed)
             continue;
          else
             break;
        }
        return 0;
    }

我愿意接受任何建议。

【问题讨论】:

  • 嗨编码器 Senjin。我最近遇到了这个问题,Darien Pardinas 的回答对我有用。如果它适合您,您应该正式接受它,以便其他人可以看到它。如果它不起作用,究竟会发生什么?你怎么修好它的?谢谢。

标签: c++ input key


【解决方案1】:

这是一个完整的例子。简而言之,您可以使用&lt;string&gt; 中的getline,当您按下Enter 键时,它也会为您提供空输入。

#include <iostream>
#include <string>

int main()
{
    while(true)
    {
        std::string in;
        getline(std::cin, in);

        if (in.empty())
        {
            std::cout << "Enter key was pressed with no message" << std::endl;
        }
        else
        {
            std::cout << "Enter key was pressed with message" << in << std::endl;
        }
    }
    return 0;
}

【讨论】:

    【解决方案2】:
    #include<iostream>
    #include<conio.h>
    #include <string>
    using namespace std;
    int main()
    {    
     char str[10];
     char a;
     int i=0;
     cout<<"\nEnter the input :-";
     do{
          a=getche();
          if(a!=13)
            {
             str[i]=a;
             i++;
            }
            else
              break;
       }
       while(a!=13);
       return 0;
    }   
    

    在上面的代码中,getch() 是一个接受单个字符输入而不将其打印到屏幕上的方法。输入时,用 13 进行检查,这是 enter 键的 ASCII 值。如果找到匹配项,它将根据您的要求终止。

    【讨论】:

      【解决方案3】:

      您可以使用 getch() 或任何其他相关字符获取字符,然后使用其 ANSCI 代码“\x0D”比较回车键

      【讨论】:

        最近更新 更多