Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3310446
  • 博文数量: 258
  • 博客积分: 9440
  • 博客等级: 少将
  • 技术积分: 6998
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-03 10:28
个人简介

-- linux爱好者,业余时间热衷于分析linux内核源码 -- 目前主要研究云计算和虚拟化相关的技术,主要包括libvirt/qemu,openstack,opennebula架构和源码分析。 -- 第五届云计算大会演讲嘉宾 微博:@Marshal-Liu

文章分类

全部博文(258)

文章存档

2016年(1)

2015年(4)

2014年(16)

2013年(22)

2012年(41)

2011年(59)

2010年(40)

2009年(75)

分类: C/C++

2009-12-25 21:39:39

C++ 容易忽略的输入输出特性
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?!



阅读(3437) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~