c++ char数组形式的字符串 与输入输出
1. c风格字符串,和strlen函数
#include "stdafx.h" #include <iostream> using std::cout; using std::endl; using std::cin; int main(void) { char dog[3] = { 'd','o','g' }; char pig[4] = { 'p','i','g','\0' }; cout << strlen(dog) << endl; cout << strlen(pig) << endl;//输出结果为3,说明strlen是字符串中除\0外有效字符的个数 cin.get(); return 0; }
2.cin从键盘输入
#include "stdafx.h" #include <iostream> using std::cout; using std::endl; using std::cin; int main(void) { const int SIZE = 15; char name[SIZE]; char dessert[SIZE]; cout << "Whats your name?" << endl; cin >> name; cout << "What's your favourate dessert?" << endl; cin >> dessert; cout << "I have some delicious " << dessert << " for you, " << name << endl; cin.get(); cin.get(); return 0; }
空格被作为空字符处理,可认为空格被丢弃,然后空字符被存入数组
3.每次读取一行的字符串输入(C++ Primer Plus Page78)
istream中的类(如cin)都提供了一些面向行的类成员函数:getline和get()。他们都读取一行输入,直到换行符,不同的是,随后getline()将丢弃换行符,而get()将换行符保留在了输入序列中。
cin.getline()
cin.getline()有两个参数,第一个是数组名称,第二个是要读取的字符数,如果这个参数是20,则只能读取到19个字符,最后一个用于存储自动添加在结尾的空字符。读取过程遇到空字符或者最大长度时停止
该函数还有三个参数的重载版本,在17章讨论
#include "stdafx.h" #include <iostream> using std::cout; using std::endl; using std::cin; int main(void) { const int SIZE = 15; char name[SIZE]; char dessert[SIZE]; cout << "Whats your name?" << endl; cin.getline(name, SIZE); cout << "What's your favourate dessert?" << endl; cin.getline(dessert, SIZE); cout << "I have some delicious " << dessert << " for you, " << name << endl; cin.get(); return 0; }
get()函数有几种变体,其中一种类似于getline,接受相同的参数,只是get不再读取并丢弃换行符,而是留在输入队列中
#include "stdafx.h" #include <iostream> using std::cout; using std::endl; using std::cin; int main(void) { const int SIZE = 15; char name[SIZE]; char dessert[SIZE]; cout << "Whats your name?" << endl; cin.get(name, SIZE).get(); cout << "What's your favourate dessert?" << endl; cin.get(dessert, SIZE).get(); cout << "I have some delicious " << dessert << " for you, " << name << endl; cin.get(); return 0; }
推荐使用cin.get而不是cin.getline(),原因是cin.getline()无法知道停止读取的原因,到低是遇到了换行符,还是数组已经满了,而cin.get()可以通过读取下一个字符,看是不是换行符,如果是,则说明读取了整行
4.对空行的处理
上面的程序,就是询问姓名和甜点,并且使用了cin.get来读取输入的程序,输入在输入姓名时,上来就回车,整个程序将一闪而过,即使是最后有一个cin.get(),也没有能够使屏显停留。原因是现代实现中,getline和get对空行的处理,是在读取空行后设置失效位(failbit)。这意味着接下来的输入将被阻断。书上说可以使用cin.clear()来恢复输入,所以如果在程序最后的cin.get()前加上一行cin.clear(),将能够再次使屏显停留?实践后发现并没有效果
5.如果读取的数据大于分配的数组长度
getline()和get()都将把余下的字符留在输入队列,且getline还会设置失效位,并且关闭后面的输入。第五、六、十七章将讨论如何避免这些问题(当前为第四章)