您的位置:首页 > 编程语言 > C语言/C++

C++ 容易忽略的输入输出特性

2009-12-25 22:01 567 查看
1 cin cout cin.get() cin.get(ch)的返回值

(1)cin ,cout 就不用多说了还是返回一个iostream对象,因此它们可以这么使用。

cin >> var1 >> var2 >>var3;

cout << var1 << var2 <<var3<<endl;

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 <iostream>

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 <iostream>

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$

5 文件输入输出

fstream中有几个函数来检查文件的状态:

eof() 返回true如果iostream 对象遇到了EOF
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: