cinのpeek putback

检查输入

cin会检查输入格式,输入与预期格式不符时,会返回false.
[cpp]  view plain copy
  1. cout << "Enter numbers: ";  
  2. int sum = 0;  
  3. int input;  
  4. while (cin >> input)  
  5.     sum += input;  
  6. cout << "Last value entered = " << input << endl;  
  7. cout << "Sum = " << sum << endl;  

上面的检查可以放入try、catch语句中。
[cpp]  view plain copy
  1. try{  
  2.     while (cin >> input)  
  3.         sum += input;  
  4. }catch(ios_base::failure &f){  
  5.     cout<<f.what()<<endl;  
  6. }  

字符串输入:getline()、get()、ignore()

getline()读取整行,读取指定数目的字符或遇到指定字符(默认换行符)时停止读取。
get()与getline()相同,接受参数也相同,均在读取到指定数目字符或换行符时停止读取。但get()将换行符停在输入流中,即下一个函数读到的首个字符将是换行符。
ignore()接受的参数也同getline(),忽略掉指定数目的字符或到换行符。
[cpp]  view plain copy
  1. char input[Limit];  
  2. cout << "Enter a string for getline() processing:\n";  
  3. cin.getline(input, Limit, '#');  
  4. cout << "Here is your input:\n";  
  5. cout << input << "\nDone with phase 1\n";  
  6. char ch;  
  7. cin.get(ch);  
  8. cout << "The next input character is " << ch << endl;  
  9. if (ch != '\n')  
  10.     cin.ignore(Limit, '\n');    // 忽略接此一行余下内容  
  11. cout << "Enter a string for get() processing:\n";  
  12. cin.get(input, Limit, '#');  
  13. cout << "Here is your input:\n";  
  14. cout << input << "\nDone with phase 2\n";  
  15. cin.get(ch);  
  16. cout << "The next input character is " << ch << endl;  


cinのpeek putback_第1张图片

例子中使用getline(),接下来的get()读到字符为3,忽略掉#;而get()之后,#在流中,所以读到字符为#。

read()

类似write()方法,读取指定数组字符。
[cpp]  view plain copy
  1. char score[20];  
  2. cin.read(score,20);  

putback()

putback()将一个字符插入到输入字符中,被插入的字符是下一条语句读到的第一个字符。
[cpp]  view plain copy
  1.    char ch;  
  2.    while(cin.get(ch))          // terminates on EOF  
  3.    {  
  4.        if (ch != '#')  
  5.            cout << ch;  
  6.        else  
  7.        {  
  8.            cin.putback(ch);    // reinsert character  
  9.            break;  
  10.        }  
  11.    }  
  12. cin.get(ch);  
  13. cout << endl << ch << " is next input character.\n";  

peek()

返回输入流中的下一个字符,但只查看不抽取。

[cpp]  view plain copy
  1. char input[100];  
  2. char ch;  
  3. int i=0;  
  4. while((ch=cin.peek())!='.'&&ch!='\n')  
  5.     cin.get(input[i++]);  
  6. input[i]='\0';  

程序遇到句号或换行符循环停止。句点或换行符仍停留在输入流中。
可见,使用peek的效果相当于先用get()读取一个字符,再用putback()将字符放入输入流中。

参见《输入流cin方法》

*参考资料:《C++ Primer Plus 5nd》

(转载请注明作者和出处:http://blog.csdn.net/xiaowei_cqu 未经允许请勿用于商业用途)

你可能感兴趣的:(cinのpeek putback)