C++ 中对于 cin.get(char) 的疑问解决方法
C++ 中对于 cin.get(char) 的疑问
#include<iostream>
using namespace std;
main()
{
char ch;
int num = 0;
cout <<"输入字符串\n";
cin.get(ch);
while(ch != '#')
{
cout << ch;
num++;
cin.get(ch);
}
cout <<endl <<num << "个字符" <<endl;
}
==============
这段代码 我相信大家都能看懂 。。我刚学C++ 对于这个字符串的处理 不太了解
我想问的是 第一次调用cin.get() 函数后输入一串字符串 "abcdef gh ijk#" 回车结束后 输出了 num的数值 但是我不明白的是 程序完成的步骤是怎么样的 如果说 第一次掉用cin.get()函数只接收 了一个字符给了下面的程序语句 while 来判断是否是 # 那判断完 是不就应该执行 cout << ch ;这条语句了 ??但是事实并不是这样 他是在输入完整个字符串敲了 回车之后 将输入的字符串输出了 并且显示了 个数 。。那么第二个cin.get()函数就没有了存在的意义,可是不是这样的 ,很显然它 是被执行了的 ,既然被执行了 那么为什么 cout << ch ;这条语句的执行 我没有在敲回车之前就看到?? 这个程序的执行顺序我有点不懂了。。。大家帮忙 指点下迷津。。谢谢了 。。。呵呵
------解决方案--------------------
#include<iostream>
using namespace std;
main()
{
char ch;
int num = 0;
cout <<"输入字符串\n";
cin.get(ch);
cout << ch << endl;//这样加一句然后分析下
while(ch != '#')
{
cout << ch;
num++;
cin.get(ch);
}
cout <<endl <<num << "个字符" <<endl;
}
#include<iostream>
using namespace std;
main()
{
char ch;
int num = 0;
cout <<"输入字符串\n";
cin.get(ch);
while(ch != '#')
{
cout << ch;
num++;
cin.get(ch);
}
cout <<endl <<num << "个字符" <<endl;
}
==============
这段代码 我相信大家都能看懂 。。我刚学C++ 对于这个字符串的处理 不太了解
我想问的是 第一次调用cin.get() 函数后输入一串字符串 "abcdef gh ijk#" 回车结束后 输出了 num的数值 但是我不明白的是 程序完成的步骤是怎么样的 如果说 第一次掉用cin.get()函数只接收 了一个字符给了下面的程序语句 while 来判断是否是 # 那判断完 是不就应该执行 cout << ch ;这条语句了 ??但是事实并不是这样 他是在输入完整个字符串敲了 回车之后 将输入的字符串输出了 并且显示了 个数 。。那么第二个cin.get()函数就没有了存在的意义,可是不是这样的 ,很显然它 是被执行了的 ,既然被执行了 那么为什么 cout << ch ;这条语句的执行 我没有在敲回车之前就看到?? 这个程序的执行顺序我有点不懂了。。。大家帮忙 指点下迷津。。谢谢了 。。。呵呵
------解决方案--------------------
#include<iostream>
using namespace std;
main()
{
char ch;
int num = 0;
cout <<"输入字符串\n";
cin.get(ch);
cout << ch << endl;//这样加一句然后分析下
while(ch != '#')
{
cout << ch;
num++;
cin.get(ch);
}
cout <<endl <<num << "个字符" <<endl;
}