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

查看:22
本文介绍了用 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

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

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