Reading in a specific format with cin(用 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 读取特定格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用 cin 读取特定格式
基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
