C++ 死循环报错的问题

来源:百度知道 编辑:UC知道 时间:2024/06/18 18:32:35
我刚学C++一个多月,最近编程遇到这个问题,我找了半天发现问题就出在这段代码上,运行时选2就正常,选1运行开始没问题,结束时执行循环就显示“输入错误,请重新输入”(choice函数里的),请高手指点下怎么改,代码如下:
#include<iostream.h>
#include<string.h>

char choice()
{
char buf[16];
for(;;)
{
cin.getline(buf,15);
if(strlen(buf)==1)
break;
cout<<"输入错误,请重新输入"<<endl;
}
return buf[0];
}

void add()
{
char arr[8];
cout<<"cin>>";
cin>>arr;
cout<<arr<<endl;
}

void add2()
{
char arr[8]="hello";
cout<<arr<<endl;
}

void main()
{

while(1)
{
cout<<"choice 1 or 2"<<endl;
char key=choice();
switch(key)
{
case '1':
add();
break;
case '2':
add2();
break;
default:
cout

#include<iostream.h>
#include<string.h>

char choice()
{
char buf[16];
for(;;)
{
cin.getline(buf,15);
if(strlen(buf)==1)
break;
cout<<"输入错误,请重新输入"<<endl;
}
return buf[0];
}

void add()
{
char arr[8];
cout<<"cin>>";
cin.getline(arr,7); //////////////修改过这行
cout<<arr<<endl;
}

void add2()
{
char arr[8]="hello";
cout<<arr<<endl;
}

void main()
{

while(1)
{
cout<<"choice 1 or 2"<<endl;
char key=choice();
switch(key)
{
case '1':
add();
break;
case '2':
add2();
break;
default:
cout<<"错误,请重新输入"<<endl;
break;
}
}
}