該函數應該讀取一個分數並將其放入數組中。如果用戶輸入'0',則該功能應該退出。我正在嘗試使用cin.peek()函數來執行此操作,但執行通常會進入if語句並且不允許用戶退出。如何正確使用cin.peek()
我應該如何正確地編寫這(我願意不使用PEEK(),我認爲這是做的最簡單的方法。)
謝謝!然而
void enterFrac(Fraction* fracs[], int& index)
{
int n, d;
char c, slash;
cout << "Enter fractions (end by entering a 0): ";
c = cin.peek();
if (c != '0')
{
cin >> n >> slash >> d;
Fraction* f = new Fraction();
f->num = n;
f->den = d;
fracs[index] = f;
index++;
}
}
偷看的這種測試()的工作原理:
#include <iostream>
using namespace std;
int main() {
char c;
int n;
char str[256];
cout << "Enter a number or a word: ";
c=cin.peek();
if ((c >= '0') && (c <= '9'))
{
cin >> n;
cout << "You have entered number " << n << endl;
}
else
{
cin >> str;
cout << " You have entered word " << str << endl;
}
return 0;
}
我添加了一個案例,我可以讓peek()正常工作,但我沒有看到是什麼原因導致了我的情況。 – Zzz