很多人做题时会遇到这样的情况,要求输入字符时随时退出循环,很多人不知道怎么办,这里介绍几种常用的方法
1、用cin.fail()控制输出,下面是代码
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
char ch;
int count = 0;
cin.get(ch);
while (cin.fail()==false)
{
count++;
cout << ch;
cin.get(ch);
}
system("pause");
return 0;
}
如果要推出循环,在输入结尾按下组合键Ctrl+Z,再按一下回车就可以推出循环了
2、在c++中不带参数的cin.get()与c语言中的getchar()作用差不多,上面的代码可以这样改一下
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
char ch;
int count = 0;
ch=cin.get();
while (ch!=EOF)
{
count++;
cout << ch;
ch=cin.get();
}
system("pause");
return 0;
}
退出循环的方式与上面一样
3、还可以这样,直接用cin
#include<iostream>
#include<ctime>
using namespace std;
int main()
{
char ch;
int count = 0;
cin>>ch;
while (cin)
{
count++;
cout << ch;
cin>>ch;
}
system("pause");
return 0;
}
以上就是控制字符输入输出的常用方法,希望对你能有帮助。