[英]struggling with cin function c++
我試圖控制cin.good()cin.fail()cin.ignore()cin.clear()等內置cin函數,但是以下代碼似乎有問題,它可以正常工作很好,但是我評論的行沒有顯示在運行時提示上。 有人可以指出我正確的方向嗎? :/
使用名稱空間std;
void main()
{
int x = 0;
char y = 0;
int ch = 0;
do
{
cout << "Press 1 for int" << endl;
cout << "Press 2 for char" << endl;
cout << "Press 3 for exit" << endl;
cout << "enter choice = ";
cin >> ch;
if (ch == 1)
{
do
{
cout << "Enter an integer only = ";
cin >> x;
if (!cin.good())
{
cout << "Please enter integer only" << endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
}
} while (cin.good() && x != 1);
}
else
if (ch == 2)
{
do
{
cout << "enter char only = ";
cin >> y;
if (cin.fail())
{ //the line below doesn't show up!
cout << "Please enter char only" << endl;
cin.clear();
cin.ignore(INT_MAX, '\n');
}
} while (!cin.fail() && y != 'e');
}
} while (ch != 3);
cout << "End of Program" << endl;
system("PAUSE"); // exit(1);
_getch();
}
cin.good()
如果流遇到諸如讀取文件末尾,不存在的文件之類的問題,則返回0。 否則為1。
cin.bad()
如果流完全不可用,則返回非零值,例如,無法打開文件(但如果流僅到達文件末尾,則不返回)。
cin.fail()
如果最后一個cin命令失敗,則返回true,否則返回false。
一個例子
int main() {
int i, j = 0;
while (1) {
i++;
cin >> j;
if (cin.fail()) return 0;
cout << "Integer " << i << ": " << j << endl;
}
現在,假設您有一個文本文件-input.txt,其內容為:
1 2 3 4 5 sahil 6 7
當您在上面的簡短程序上運行時,結果將是:
整數1:1整數2:2整數3:3整數4:4整數5:5
它不會在第5個值之后繼續,因為它在讀取第6個字后退出,因為它不是整數:cin.fail()成立。
cin.clear()和cin.ignore()
int age;
for (;;) {
cout << "Please enter your age: ";
if (cin >> age) {
break;
} else {
cout << "Please enter a valid integer age" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
請參閱此文件以用於文件處理 :
壞()
如果讀取或寫入操作失敗,則返回true。 例如,在我們嘗試寫入未打開以進行寫入的文件的情況下,或者在嘗試寫入的設備沒有剩余空間的情況下。
失敗()
在與bad()相同的情況下,以及在發生格式錯誤的情況下(例如,當我們嘗試讀取整數時提取了字母字符時)都返回true。
EOF()
如果要讀取的文件已到達末尾,則返回true。
好()
它是最通用的狀態標志:在調用任何先前函數將返回true的相同情況下,它返回false。 注意,好的和壞的並不完全相反(好的一次檢查更多的狀態標志)。
成員函數clear()可用於重置狀態標志。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.