What is the cin analougus of scanf formatted input?(scanf 格式输入的 cin 类比是什么?)
问题描述
使用 scanf,通常有一种直接获取格式化输入的方法:
With scanf there's, usually, a direct way to take formatted input:
1) 大于 0 且小于 1 的实数行.以x"结尾,例如:0.32432523x
1) line with a real number higher than 0, and less than 1. Ending on 'x', e.g: 0.32432523x
scanf("0.%[0-9]x", &number);
2) 行表示格式为:30+28=58
scanf(":%d+%d=%99s", &number1, &number2, &total);
cin的解决方法是什么,只用标准库?
What is the cin solution, using only the standard library?
推荐答案
使用 >> 操作符读取 cin.
Use the >> operator to read from cin.
int number1, number2;
std::string text;
char plus, equals;
std::cin >> number1 >> plus >> number2 >> equals >> text;
if (!std::cin.fail() && plus == '+' && equals == '=' && !text.empty())
std::cout << "matched";
它不如 scanf 好,因为您必须自己验证 scanf 字符串中的任何文字.用流来做这件事几乎肯定会比 scanf 要多得多的代码行.
It's not as good as scanf because you'd have to verify any literals that were in the scanf string yourself. Doing it with streams will almost certainly be a lot more lines of code than scanf.
我会使用 scanf.
I would use scanf.
这篇关于scanf 格式输入的 cin 类比是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:scanf 格式输入的 cin 类比是什么?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
