5.16 textin1.cpp
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0; // use basic input
cout << "Enter characters; enter # to quit:\n";
cin >> ch; // get a character
while (ch != '#') // test the character
{
cout << ch; // echo the character
++count; // count the character
cin >> ch; // get the next character
}
cout << endl << count << " characters read\n";
// get rid of rest of line
// while (cin.get() != '\n')
// ;
//cin.get();
return 0;
}
- 本函数展示了利用while循环来读取键盘输入
- 程序读取键盘的输入,并将其显示出来,当读取到“#”字符时停止读取
- 本程序存在的不足是在读取到空格符时无法显示和计数
5.17 textin2.cpp
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cout << "Enter characters; enter # to quit:\n";
cin.get(ch); // use the cin.get(ch) function
while (ch != '#')
{
cout << ch;
++count;
cin.get(ch); // use it again
}
cout << endl << count << " characters read\n";
// get rid of rest of line
// while (cin.get() != '\n')
// ;
//cin.get();
return 0;
}
- 该代码对上述代码进行了修改,采用了cin.get()函数捕获输入中的空格,并对其进行显示
5.18 textin3.cpp
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cin.get(ch); // attempt to read a char
while (cin.fail() == false) // test for EOF
{
cout << ch; // echo character
++count;
cin.get(ch); // attempt to read another char
}
cout << endl << count << " characters read\n";
return 0;
}
- 改代码修改了循环结束的条件,原代码以“#”作为结束判定条件,这在有些时候并不适用
-
cin.fail()用来读取结束条件EOF(检测文件尾)
-
一般PC编程系统将ctrl+z视作结束条件
5.19 textin4.cpp
#include <iostream>
int main(void)
{
using namespace std;
int ch; // should be int, not char
int count = 0;
while ((ch = cin.get()) != EOF) // test for end-of-file
{
cout.put(char(ch));
++count;
}
cout << endl << count << " characters read\n";
return 0;
}
- 该代码又对上述代码做了改良,将循环结束条件又做了更改
- 使该代码可以输入int类型的字符,并将cin.get()代替cin.get(char),用cout.put()代替cout
- 用EOF代替cin.fail()测试,注意:EOF不表示输入中的字符,而是指没有字符
5.20 nested.cpp
#include <iostream>
const int Cities = 5;
const int Years = 4;
int main()
{
using namespace std;
const char * cities[Cities] = // array of pointers
{ // to 5 strings
"Gribble City",
"Gribbletown",
"New Gribble",
"San Gribble",
"Gribble Vista"
};
int maxtemps[Years][Cities] = // 2-D array
{
{96, 100, 87, 101, 105}, // values for maxtemps[0]
{96, 98, 91, 107, 104}, // values for maxtemps[1]
{97, 101, 93, 108, 107}, // values for maxtemps[2]
{98, 103, 95, 109, 108} // values for maxtemps[3]
};
cout << "Maximum temperatures for 2008 - 2011\n\n";
for (int city = 0; city < Cities; ++city)
{
cout << cities[city] << ":\t";
for (int year = 0; year < Years; ++year)
cout << maxtemps[year][city] << "\t";
cout << endl;
}
// cin.get();
return 0;
}
- 该代码讲解了二维数组的使用方法
- 首先声明一个char指针数组,使得该数组中的每一个元素都是一个char指针,可被初始化为一个字符串的地址
- 之后则是使用了两个for循环嵌套,输出二维数组中的每一个元素