您的位置:首页 > 编程语言 > C语言/C++

C/C++在控制台下让用户输入正确的字符后,则返回,否则一直提示输入

2015-03-28 23:17 246 查看
1.不用goto语句的情况下可以用下面的方法。

#include<stdio.h>

#include<conio.h>

int main(void)

{

 bool b = true;

 while(b)

 {

  char ch;

  printf("Inputacharacter:");

  ch = getch();

  if(ch==1)

  {

   b = false;

  }

  else

  {

   printf("\nYouinputa'%c'\n",ch);

  }

 }

 return 0;

}

如果是字符串的话,请用下面的代码:<pre class="cpp" name="code"> #include <iostream>

using namespace std;

void main()

{

 bool b = true;

 while(b)

 {

  char s[50];//字符数组,用于存放字符串的每一个字符

  cout<<"Please input a string"<<endl;

  cin>>s;//注意cin.get(s,50);cin.get()是保留回车在输入流队列中的.而cin是丢弃回车的.

  if(strcmp(s , "123") == 0)

  {

   b = false;

  }

  else

  {

   cout<<"The string you input is:"<<s<<endl;

  }

 }

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 控制台
相关文章推荐