1 cin cout cin.get() cin.get(ch)的返回值
(1)cin ,cout 就不用多说了还是返回一个iostream对象,因此它们可以这么使用。
cin >> var1 >> var2 >>var3;
cout << var1 << var2 <
cin.get() 没有参数时,返回值是一个整数,所以通常这么用
while((ch=cin.get()) != EOF)
{
cout << ch;
}
cin.get(ch)代参数时,返回的也是一个iostream对象,因此可以这么用
cin.get(a).get(b).get(c);
2 cin.get(buffer, num, terminate) cin.getline(buffer, num, terminate)的区别
注:terminate 一般为 '\n'
二者都是每次读取一行字符,或是碰到ternimate指定的字符终止或是读的字符数超过num - 1终止。
区别是cin.get会把terminate留在缓冲区中,因此下次读到的第一个字符就是terminate字符,相反,cin.getline()则会丢弃缓冲区中的terminate字符。
#include
using namespace std;
int main()
{
char stringOne[255];
char stringTwo[255];
cout << “Enter string one:”;
cin.get(stringOne,255);
cout << “String one: “ << stringOne << endl;
cout << “Enter string two: “;
cin.getline(stringTwo,255);
cout << “String two: “ << stringTwo << endl;
cout << “\n\nNow try again...\n”;
cout << “Enter string one: “;
cin.get(stringOne,255);
cout << “String one: “ << stringOne<< endl;
cin.ignore(255,’\n’);
cout << “Enter string two: “;
cin.getline(stringTwo,255);
cout << “String Two: “ << stringTwo<< endl;
return 0;
}
看输入输出结果:
Enter string one:once upon a time
String one: once upon a time
Enter string two: String two:
Now try again...
Enter string one: once upon a time
String one: once upon a time
Enter string two: there was a
String Two: there was a
3 两个比较有用的函数:peek(), putback() 和 ignore()
cin.peek(ch); 忽略字符ch
cin.putback(ch); 把当前读到的字符替换为ch
cin.ignore(num, ch); 从当前字符开始忽略num个字符,或是碰到ch字符开始,并且把ch字符丢丢掉。
#include
using namespace std;
int main()
{
char ch;
cout << “enter a phrase: “;
while ( cin.get(ch) != 0 )
{
if (ch == ‘!’)
cin.putback(‘$’);
else
cout << ch;
while (cin.peek() == ‘#’)
cin.ignore(1,’#’);
}
return 0;
}
输入输出结果:
enter a phrase: Now!is#the!time#for!fun#!
Now$isthe$timefor$fun$
4 cout.put() cout.write()
与输入相同,cout.put(ch) 返回一个iosream对象,因此可以连续使用
cout.write(text,num) 输出text中的num个字符,如果num > strlen(text), 则后面输出的是text之后的内存中的随机的字符。
#include
#include
using namespace std;
int main()
{
char One[] = “One if by land”;
int fullLength = strlen(One);
int tooShort = fullLength -4;
int tooLong = fullLength + 6;
cout.write(One,fullLength) << endl;
cout.write(One,tooShort) << endl;
cout.write(One,tooLong) << endl;
return 0;
}
输入结果:
One if by land
One if by
One if by land i?!