用 cin 读取特定格式
如何使用 cin 读取特定格式的内容?示例:-读取一个复数,我希望用户像往常一样输入它:x+yi,所以我想要这样的东西:cin>>x>>"+">>y>>"i";但这给出了一个错误.什么是正确的方法?帮助非常感谢.
How can i read in a specific format using cin? Example:-for reading a complex number, I would like the user to enter it as usual:x+yi, so i want something like this: cin>>x>>"+">>y>>"i"; But this is giving an error.What is the right way?Help greatly appreciated.
推荐答案
一个非常简单的解决方案:
A very simple solution:
char plus,img;
double x,y;
cin>> x >> plus >> y >> img;
if (plus!='+' || img!='i') ...error
在现实生活"代码中,您构建/使用 class complex
,并重载运算符 >>.
In "real life" code you build/use a class complex
, and overload the operator >>.
我在 Ideone 中尝试:http://ideone.com/ZhSprF
I try it in Ideone: http://ideone.com/ZhSprF
#include <iostream>
using namespace std;
int main()
{
char plus{},img{};
double x{},y{};
cin>> x >> plus >> y >> img;
if (plus!='+' || img!='i')
cout << "
Error: "<< "x=" << x <<", plus=" << plus <<", y=" << y <<", img=" << img;
else
cout << "
Complex: " << x << plus << y << img;
return 0;
}
stdin: 3 + 4i
--> stdout: 复杂: 3+4i
stdin: 3 + 4i
--> stdout: Complex: 3+4i
stdin: 1E4L1e3g
--> stdout: 错误: x=10000, plus=L, y=1000, img=g
stdin: 1E4L1e3g
--> stdout: Error: x=10000, plus=L, y=1000, img=g
stdin: a+3i
--> stdout: 错误: x=0, plus=, y=0, img=
stdin: a+3i
--> stdout: Error: x=0, plus=, y=0, img=
stdin: 1e3+93E-2i
--> stdout: Complex: 1000+0.93i
stdin: 1e3+93E-2i
--> stdout: Complex: 1000+0.93i
相关文章