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?!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值