C++;在一条线上测试CIN 我最近开始教自己C++,在编写了大量的用户输入代码之后,我想知道是否有更简单的处理方法。
例如,通常的做法如下:C++;在一条线上测试CIN 我最近开始教自己C++,在编写了大量的用户输入代码之后,我想知道是否有更简单的处理方法。,c++,input,C++,Input,例如,通常的做法如下: #include <iostream> using namespace std; int inp; int guess = 13; void main(){ cout << "Guess a number: "; cin >> inp; if (inp == guess) cout << endl << "Nice."; } #包括 使用名称空间std; int-in
#include <iostream>
using namespace std;
int inp;
int guess = 13;
void main(){
cout << "Guess a number: ";
cin >> inp;
if (inp == guess)
cout << endl << "Nice.";
}
#包括
使用名称空间std;
int-inp;
int guess=13;
void main(){
cout>inp;
如果(inp==猜测)
简言之:不,你不可能随心所欲
您需要了解,>
实际上是的函数调用
template<typename T>
std::istream& operator>>(std::istream& is, T& result);
后者用于检查流状态,不提取任何用户输入
要比较输入,需要从排在第一位的std::istream
中提取结果。好的,您可以在一行中完成,但实际上不需要。但这里还是有一些示例
//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;
}
但是你真的希望保持简单,因为这会在一段时间后让别人和你自己都感到困惑。你想让你的代码尽可能简单不,你不能这样做。操作符>>()
实际上是一个函数调用。如果(cin>>inp&&inp==guess),你可以做…
有点离题,但是-使用int作为main的返回类型比使用void更好吗?我一直使用void,因为我不认为只返回0有什么意义。但是在我从其他人那里看到的大多数代码中,他们对main使用整数返回类型。@NeonWizardvoid
不是一个定义良好的返回类型rmain()
,只是visual studio接受了它。而且有些编译器不接受没有返回类型的main()
,因此最好使用int main()
而不是void main()
我做了一些研究,发现main返回的整数基本上是错误代码。0表示一切正常。
template<typename T>
bool operator==(const std::istream&,const T& x);
//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;
}
#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;
}
if( cin >> inp && inp == guess )