Zzz*_*Zzz 8 c++ struct cin peek
This function is supposed to read a fraction and place it in an array. If the user enters '0' the function is supposed to exit. I am trying to do this using the cin.peek() function but execution always goes into the if statement and doesn't allow the user to exit.
How should I properly code this (I am open to not using peek(), I thought it was the simplest way of doing it.)
Thanks!
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
This test of peek() works however:
#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;
}
Run Code Online (Sandbox Code Playgroud)
Die*_*ühl 12
您使用以下两个问题std::istream::peek():
std::ws:(std::cin >> std::ws).peek().std::istream::peek()不是char.相反,它是一个std::char_traits<char>::int_type(这是一个奇特的拼写int).结果可能是,例如,std::char_traits<char>::eof()并且如果值'0'恰好为负(我不知道它的任何平台;但是,例如,我名字中的有趣字符'ü'在char签名的平台上是负值)你也不会得到正确的结果.也就是说,您通常将结果std::istream::peek()与结果进行比较std::char_traits<char>::to_int_type(),即您使用以下内容:std::cin.peek() == std::char_traits<char>::to_int_type('0')也就是说,你的程序不会检查它是否能成功读取以斜线分隔的分母和分母.你总是想验证阅读是否成功,例如,使用类似的东西
if ((std::cin >> nominator >> slash >> denominator) && slash == '/') {
...
}
Run Code Online (Sandbox Code Playgroud)
只是为了娱乐,你可以创建一个操纵器来测试角色是斜线,的确如下:
std::istream& slash(std::istream& in) {
if ((in >> std::ws).peek() != std::char_traits<char>::to_int_type('/')) {
in.setstate(std::ios_base::failbit);
}
return in;
}
Run Code Online (Sandbox Code Playgroud)
这样,您就可以封装斜杠测试.如果你需要在多个地方使用它,这是非常方便的.
| 归档时间: |
|
| 查看次数: |
38803 次 |
| 最近记录: |