用cin读取特定的格式 [英] Reading in a specific format with cin

查看:251
本文介绍了用cin读取特定的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能读取使用cin的特定格式?
例如:为了阅读一个复杂的数字,我希望用户像往常一样输入:x + yi,
所以我想要这样的东西:
cin >> x >> + >> Y >> I;
但是这是一个错误,什么是正确的方式?非常感谢。

解决方案

一个非常简单的解决方案:

  char plus,img; 
double x,y;
cin>> x>>加>> y>> IMG;
if(plus!='+'|| img!='i')... error

在真实生活代码中,您构建/使用 class complex ,并重载运算符>>。 $ b

我在Ideone尝试: http:// ideone .com / ZhSprF

  #include< iostream> 
使用namespace std;

int main()
{
char plus {},img {};
double x {},y {};
cin>> x>>加>> y>> IMG;
if(plus!='+'|| img!='i')
cout<< \\\
Error:<< x =<< x<<,plus =<<加上<<,y =<< y<<,img =<< IMG;
else
cout<< \ nComplex:<< x<<加上<< y< IMG;


return 0;

stdin: 3 + 4i - > stdout: Complex:3 + 4i



1E4L1e3g - > stdout:错误:x = 10000,plus = L,y = 1000,img = g



stdin: a + 3i - > stdout:错误:x = 0,plus =,y = 0,img =



stdin: 1e3 + 93E-2i - > stdout: Complex:1000 + 0.93i


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

In "real life" code you build/use a class complex, and overload the operator >>.

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 << "\nError: "<< "x=" << x <<", plus="  << plus <<", y="  << y <<", img="  << img;
    else
        cout << "\nComplex: " << x << plus << y << img;


    return 0;
}

stdin: 3 + 4i --> stdout: Complex: 3+4i

stdin: 1E4L1e3g --> stdout: Error: x=10000, plus=L, y=1000, img=g

stdin: a+3i --> stdout: Error: x=0, plus=, y=0, img=

stdin: 1e3+93E-2i --> stdout: Complex: 1000+0.93i

这篇关于用cin读取特定的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆