如何使用 cin 以特定格式读取内容? 示例:-为了读取复数,我希望用户照常输入:x+yi, 所以我想要这样的东西: cin>>x>>"+">>y>>"i"; 但这给出了错误。正确的方法是什么?非常感谢帮助。
最佳答案
一个非常简单的解决方案:
char plus,img;
double x,y;
cin>> x >> plus >> y >> img;
if (plus!='+' || img!='i') ...error
在“现实生活”代码中,您构建/使用类复合体
,并重载运算符>>。
我在 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 << "\nError: "<< "x=" << x <<", plus=" << plus <<", y=" << y <<", img=" << img;
else
cout << "\nComplex: " << x << plus << y << img;
return 0;
}
标准输入:3 + 4i
--> 标准输出:复杂:3+4i
标准输入:1E4L1e3g
--> 标准输出:错误:x=10000,plus=L,y=1000,img=g
stdin: a+3i
--> stdout: 错误: x=0, plus=, y=0, img=
标准输入:1e3+93E-2i
--> 标准输出:复杂:1000+0.93i
关于c++ - 使用 cin 以特定格式读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14901678/