关于循环和文本输入的问题
c++吧
全部回复
仅看楼主
level 11
xhch0930 楼主
RT
我是看到c++ primer plus第六版的第五章 5.5循环和文本输入 这一节时遇到问题
程序如下:
#include <iostream>
using namespace std;
int main()
{
char ch;
int count = 0;
cout << "enter chars;and enter # to quit:\n";
cin.get(ch);
while (ch != '#')
{
cout << ch;
++ count;
cin.get(ch);
}
cout << endl << count << "chars read\n";
system ("pause");
return 0;
}
输入:
do u want some #2 pies?
输出:
do u want some
15 chars read
在这之前我都是运用
数组+while循环完成这样的程序 例如让用户输入名字然后显示每一个字母以及它的UNICODE编码
但是在这个程序里我有些地方不明白 比如
cin.get(ch);
while (ch != '#')
{
cout << ch;
++ count;
cin.get(ch);
}
这一段 为什么cin.get(ch);可以使输入的字符(串)被读取进循环里?循环体内外的cin.get(ch);是什么意思?有什么作用? 我同样对count在循环和读数中的作用不太明白。
求教了[呵呵]多谢~I
2013年11月03日 11点11分 1
level 11
xhch0930 楼主
p.s. 就像上文提的如果是我 我会这样写
#include <iostream>
using namespace std;
int main()
{
char ch[40]; //if input <= 39,ok
int i = 0;
cout << "enter chars;and enter # to quit:\n";
cin.getline(ch,40);
while (ch[i] != '#')
{
cout << ch[i];
i ++;
}
cout << endl << i << "chars read\n";
system ("pause");
return 0;
}
这两个程序有什么区别?I
2013年11月03日 11点11分 2
BTW 一楼 我在写“输入”的时候 后面跟的语句多打了个空格 抱歉
2013年11月03日 11点11分
没人么[泪]
2013年11月03日 11点11分
真没人哇T∧T
2013年11月04日 03点11分
1