【发布时间】:2012-11-21 20:50:00
【问题描述】:
这个函数应该读取一个分数并将其放入一个数组中。如果用户输入“0”,则该函数应该退出。我正在尝试使用 cin.peek() 函数执行此操作,但执行总是进入 if 语句并且不允许用户退出。
我应该如何正确编码(我愿意不使用 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++;
}
}
不过,这个 peek() 测试有效:
#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() 正常工作的案例,但我看不出是什么导致了我的案例中的问题。