简体   繁体   English

C ++在一行上测试CIN

[英]C++ test CIN on one line

I've recently started teaching myself C++, and after having written a lot of user input code, it's made me wonder if there's a simpler way of handling it. 我最近开始自学C ++,在编写了大量用户输入代码后,我想知道是否有更简单的方法来处理它。

For example, the normal way of doing it would be like this: 例如,正常的做法是这样的:

#include <iostream>
using namespace std;

int inp;
int guess = 13;

void main(){
    cout << "Guess a number: ";
    cin >> inp;
    if (inp == guess)
        cout << endl << "Nice.";
}

But what I want to do is: 但我想做的是:

#include <iostream>
using namespace std;

int guess = 13;

void main(){
    cout << "Guess a number: ";
    if (cin == guess)
        cout << endl << "Even nicer.";
}

Is there a way to do this? 有没有办法做到这一点? Or this that just improper C++ standard? 或者这只是不恰当的C ++标准?

In short: No, it's not possible to do as you want it. 简而言之:不,不可能按照你的意愿去做。

You need to understand, that >> is actually a function call of 你需要明白, >>实际上是一个函数调用

template<typename T>
std::istream& operator>>(std::istream& is, T& result);

and == is a function call to ==是函数调用

template<typename T>
bool operator==(const std::istream&,const T& x);

Where the latter is used to check the stream state, and doesn't extract any user input. 其中后者用于检查流状态,并且不提取任何用户输入。

To compare the input the result needs to be extracted from the std::istream in 1st place. 要比较输入,需要从第一个位置的std::istream中提取结果。

Well you can do it in one line but you don't really need to. 那么你可以在一行中完成,但你并不需要。 But here are some examples anyway 但无论如何,这里有一些例子

//This will work for a char
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    char test = 'a';
    if (getch()== test)
        cout<<"\n Works";
    return 0;
}

And if you really want 如果你真的想要

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    int x =1;
    int y;
    for( cin >> y ; x == y ; )
    {
        cout<<"\n Works";
        break;
    }
    return 0;
}

Or as NathanOliver said you could simply do this 或者正如NathanOliver所说,你可以简单地做到这一点

if( cin >> inp && inp == guess )

But really you want to keep it simple as this will confuse others as well as yourself after some time. 但实际上你想保持简单,因为这会在一段时间后让别人和你自己混淆。 You want to leave your code as easy as possible 您希望尽可能简单地保留代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM