检查输入
cin会检查输入格式,输入与预期格式不符时,会返回false.
cout << "Enter numbers: "; int sum = 0; int input; while (cin >> input) sum += input; cout << "Last value entered = " << input << endl; cout << "Sum = " << sum << endl;
上面的检查可以放入try、catch语句中。
try{ while (cin >> input) sum += input; }catch(ios_base::failure &f){ cout<<f.what()<<endl; }
字符串输入:getline()、get()、ignore()
getline()读取整行,读取指定数目的字符或遇到指定字符(默认换行符)时停止读取。
get()与getline()相同,接受参数也相同,均在读取到指定数目字符或换行符时停止读取。但get()将换行符停在输入流中,即下一个函数读到的首个字符将是换行符。
ignore()接受的参数也同getline(),忽略掉指定数目的字符或到换行符。
char input[Limit]; cout << "Enter a string for getline() processing:\n"; cin.getline(input, Limit, '#'); cout << "Here is your input:\n"; cout << input << "\nDone with phase 1\n"; char ch; cin.get(ch); cout << "The next input character is " << ch << endl; if (ch != '\n') cin.ignore(Limit, '\n'); // 忽略接此一行余下内容 cout << "Enter a string for get() processing:\n"; cin.get(input, Limit, '#'); cout << "Here is your input:\n"; cout << input << "\nDone with phase 2\n"; cin.get(ch); cout << "The next input character is " << ch << endl;
例子中使用getline(),接下来的get()读到字符为3,忽略掉#;而get()之后,#在流中,所以读到字符为#。
read()
类似write()方法,读取指定数组字符。
char score[20]; cin.read(score,20);
putback()
putback()将一个字符插入到输入字符中,被插入的字符是下一条语句读到的第一个字符。
char ch; while(cin.get(ch)) // terminates on EOF { if (ch != '#') cout << ch; else { cin.putback(ch); // reinsert character break; } } cin.get(ch); cout << endl << ch << " is next input character.\n";
peek()
返回输入流中的下一个字符,但只查看不抽取。
char input[100]; char ch; int i=0; while((ch=cin.peek())!='.'&&ch!='\n') cin.get(input[i++]); input[i]='\0';
程序遇到句号或换行符循环停止。句点或换行符仍停留在输入流中。
可见,使用peek的效果相当于先用get()读取一个字符,再用putback()将字符放入输入流中。