首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

在学C++Primer plus 一个有关问题

2012-09-09 
在学C++Primer plus 求高手指教一个问题[codeC/C++][/code]//twoarg.cpp -- a function with 2 arguments

在学C++Primer plus 求高手指教一个问题
[code=C/C++][/code]
//twoarg.cpp -- a function with 2 arguments
#include <iostream>
using namespace std;
void n_chars(char,int);
int main()
{
int times;
char ch;

cout<<"Enter a character: ";
cin>>ch;
while(ch!='q')
{
cout<<"Enter an integer: ";
cin>>times;
n_chars(ch,times);
cout<<"\nEnter another character or press the"
" q-key to quit:";
cin>>ch;
}
cout<<"The value of times is "<<times<<".\n";
cout<<"Bye\n";
return 0;
}

void n_chars(char c,int n)
{
while(n-->0)
cout<<c;
}[code=C/C++][/code]

这个是例题7.3
现在想问一下 如果刚开始输入的是两个字符如:wa 
程序就会一直运行!!!
cin>>ch;不是一个一个字符读取 然后执行while循环的吗
为什么输入两个字符就不对了?

[解决办法]

C/C++ code
#include <iostream>using namespace std;void n_chars(char,int);int main(){    int times;    char ch;    cout<<"Enter a character: ";    cin>>ch;//---->这里如果输入的是pi的话,也就是两个字符,ch为p这个好理解吧(如果输入诸如p9可以保证正常运行)    while(ch!='q')    {        cout<<"Enter an integer: ";        cin>>times;//然后这里默认的times 的值就不确定了,因为第二个字符i不是整数,times也没有初始化        n_chars(ch,times);//然后这里就传了一个随机的整数的进去了,这个数还很大,导致一直输出p        cout<<"\nEnter another character or press the"        " q-key to quit:";        cin>>ch;//因为编译器是遇到错误就重新开始读字符的,然后它又回到字符p开始读,结果这里始终为p循环一直执行    }    cout<<"The value of times is "<<times<<".\n";    cout<<"Bye\n";    return 0;}void n_chars(char c,int n){    while(n-- > 0)        cout<<c;} 

热点排行