注册 登录
编程论坛 C++教室

关于getche问题

罗彬 发布于 2007-03-14 22:48, 620 次点击
请问一下为什么把getche变为getchar 或者cin.get()的时候就永远按回车都不能够把结果打出来,
如果变为getchar应该如何变程序,请各位高手指教.
#include<iostream.h>
#include<conio.h>
using namespace std;
main()
{
int char_count=0;
int word_count=0;
char ch;
cout<<"please enter a string:\n";
while((ch=getche())!='\r')
{
char_count++;
if (ch==' '||ch=='\t')
{word_count++;}

}
cout<<"\n This string contains"<<char_count
<<"character"<<endl;
cout<<"This string consists of"<<word_count+1
<<"word"<<endl;
return 0;
}
2 回复
#2
bill88882007-03-15 00:29

把while((ch=getche())!='\r')换成while((ch=getchar())!='\n')就可以了
或者说不用回车作为string结束符可以了
\r只是实现了回车,也就是从一行头重新显示,\r所实现的功能和enter所实现的功能是不同的。
\n 就是回车和换行合并在一齐了,用于控制显示格式
注意\r和\n不是完全一样的,他们的ASCII值都不相同

#3
罗彬2007-03-15 12:53

非常感谢,以后还请多指教

1