如何在C ++中捕获字符输入? [英] How do I trap character inputs in C++?

查看:77
本文介绍了如何在C ++中捕获字符输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是我计划的一部分。我的问题是我的程序没有陷阱或阻止字符输入。我声明char opt ='0'进入主菜单。如果用户输入字符,则用户必须再次输入。如何捕获它。



This is just a portion of my program. My problem is that my program doesn't trap or block character inputs. I declare char opt='0' to go to main menu. If the user inputs a character the user must input again. How to trap it.

case '2':
    {
      if(y==1)
       {
         view();
       }
      else
      {
        system("cls");
        cout<<"\n\n\t\t------------------------------\n\n";
        cout<<"\t unable to view the record!!!!";
        cout<<"\n\n\t\t------------------------------\n\n";
        int v=1;
        while(v!=0&&!cin&&cin.fail()) //I used this for trapping a chararacter but it doesn't work.
        {
             cout<<"press 0 to go menu: ";
              cin.clear(); // clear the error
             // clear the input stream
              cin.ignore(100,'\n');
              cin>>v;
        }
       system("cls");
    }

   break;
}

推荐答案

阅读本文。



http://www.opensourceforu.com/2014/03/write-conio-h-gnulinux/ [ ^ ]



如果您使用的是Windows,请将代码写入#include< conio.h>并使用kbhit& getch接受按键而不阻塞。这篇文章描述了如何在Linux(以及可能的其他POSIX)系统上做同样的事情。
Read this.

http://www.opensourceforu.com/2014/03/write-conio-h-gnulinux/[^]

If you're on Windows, write your code to #include <conio.h> and use kbhit & getch to accept keypresses without blocking. The article describes how to do the same on Linux (and possibly other POSIX) systems.


如果我有你想要的,你想让用户输入一个数字从菜单中执行相应的操作。在伪代码中你想要的是:



If I've got what you've asking right you want to allow a user to enter a number from a menu and have the corresponding action carried out. In pseudo code what you want is something like:

loop until doomsday
	try and get an integer from a stream
	if the stream hasn't failed
		do something with the integer
	otherwise if the stream is in a failed state from incorrect input
		reset the stream
		clear out the gash data that caused the stream to fail





循环直到世界末日可以表示为流式样的东西循环直到流进入一个奇怪的国家。 而(std :: cin)将为附加到 stdin 的流执行此操作。



尝试从流中获取整数只是提取一个整数:



int number; std :: cin>>号码;



会为你做这件事。



查看流未失败的情况与循环控制类似。 if(std :: cin)会出于同样的原因这样做。



检查流是否在无效状态有点困难。我们不能只检查流是否已经失败,我们必须检查它是否由于文件结束条件而失败,或者因为基础流缓冲区已经搞砸了。我们可以通过以下测试来做到这一点:



if(std :: cin.fail()&&!std :: cin .bad()&&!std :: cin.eof())



清除流上的错误很简单: std :: cin.clear()会这样做。我们可以通过将输入读入字符串并丢弃它来摆脱输入不正确的输入: std :: string junk; std :: getline(std :: cin,junk);



总结我们得到:





"loop until doomsday" can be represented for stream style stuff as "loop until the stream is in a strange state". while( std::cin ) will do that for the stream attached to stdin.

"try and get an integer from a stream" is just extracting an integer:

int number; std::cin >> number;

will do that for you.

Checking to see that the stream hasn't failed is similar to the loop control. if( std::cin ) will do that for the same reasons.

Checking that the stream is in an invalid state is a bit harder. We can't just check that the stream has failed, we have to check that it's not failed because of an end of file condition or because the underlying stream buffer has screwed up. We can do this with the following test:

if( std::cin.fail() && !std::cin.bad() && !std::cin.eof() )

Clearing the error on the stream is easy: std::cin.clear() will do that. We can get rid of the input that was entered incorrectly by reading it into a string and discarding it: std::string junk; std::getline( std::cin, junk );

Putting it all together we get:

#include <iostream>
#include <string>

int main()
{
	while( std::cin )
	{
		int number; std::cin >> number;
		if( std::cin )
		{
			std::cout << "You entered: " << number << std::endl;
		}
		else
		{
			if( !std::cin.eof() && !std::cin.bad() && std::cin.fail() )
			{
				std::cout << "You didn't enter a number" << std::endl;
				std::cin.clear();
				std::string junk;
				std::getline( std::cin, junk );
			}
		}
	}
}





您可以简化品味和插入自己的代码品尝。如果您编译并运行上面的代码,它将回显您输入到 stdout 的任何整数,并拒绝任何其他输入。要退出程序,请在Windows上使用CTRL-Z,或在unixy系统上使用CTRL-D。请注意,它不会处理所有错误条件(输入带小数点的数字并查看)但您也可以收紧代码以处理它。



为了真正了解溪流,我建议购买,阅读和内部消化Klause Kreft和Angelika Langer的标准IOStreams和Locales 。它真的很好地报道了我如何处理溪流...



You can simplify that to taste and insert your own code to taste. If you compile and run the code above it'll echo any integers you input to stdout and reject any other input. To exit the program use CTRL-Z on windows or CTRL-D on unixy systems. Note that it won't handle all error conditions (enter a number with a decimal point and see) but you can tighten the code up to handle that as well.

To really understand streams I'd recommend buying, reading and inwardly digesting Standard IOStreams and Locales by Klause Kreft and Angelika Langer. It's really good coverage of "how do I do stuff with streams..."


这篇关于如何在C ++中捕获字符输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆