如何用C++为这种情况编写一个严格的函数
How can I write a rigorous function for this case in C++
函数很简单,只需取一个格式为(1,2)的字符串,就可以从中得到1,2作为两个整数。
但是如何写得严谨呢?比如可以检测到无效输入。但我不想一个字符一个字符地阅读,有没有默认的功能?
我知道的最简单的方法是将这些内容复制粘贴到标题中,这样可以直观地"流式输入"文本:
#include <iostream>
#include <string>
#include <array>
#include <cstring>
template<class e, class t, int N>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e(&stringlit)[N]) {
std::array<e, N-1> buffer; //get buffer
in >> buffer[0]; //skips whitespace
if (N>2)
in.read(&buffer[1], N-2); //read the rest
if (strncmp(&buffer[0], stringlit, N-1)) //if it failed
in.setstate(in.rdstate() | std::ios::failbit); //set the state
return in;
}
template<class e, class t>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e& charlit) {
e buffer; //get buffer
in >> buffer; //read data
if (buffer != charlit) //if it failed
in.setstate(in.rdstate() | std::ios::failbit); //set the state
return in;
}
//redirect mutable char arrays to their normal function
template<class e, class t, int N>
std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, e(&carray)[N]) {
return std::operator>>(in, carray);
}
那么你的代码就是:
if (stream >> '(' >> leftnum >> ',' >> rightnum >> ')' )
; //success
else
; //invalid input
一种更常见的方式是正则表达式:
std::string line;
std::getline(stream, line);
std::regex re("(([0-9]+),([0-9]+))");
std::smatch match;
if (std::regex_match(stream, match, re) && match.size() > 1)
; //success
else
; //invalid input
int main() {
int a, b;
if(std::scanf("(%d,%d)", &a, &b) != 2) {
// Error ! Recover or give up.
}
// a and b contain your values.
return 0;
}
这当然可以扩展到任何格式,但std::scanf
正是您所需要的。
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何仅为一个函数添加延迟
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 我需要将多个函数组合为一个函数
- 在C++中声明一个函数时,它需要有函数本身的参数吗
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 一个函数,用于查找字符串1包含字符串2 c++的次数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 编写一个函数以使用 n 百分比的 CPU 使用率
- 将 N-arg 函数包装到另一个函数中
- 如何封装一个函数,以便它只能由同一类中的一个其他函数调用?
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- C++从另一个函数退出函数
- 编写一个函数来删除单链表中的节点(尾部除外),仅授予对该节点的访问权限
- 视觉我希望一个函数在另一个函数C++中进行计算
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 在另一个函数 (c++) 中调用变量
- 如何在另一个函数中使用返回值作为参数?
- 如何包装一个函数以适应另一个函数的所需类型
- 创建一个函数的 Python 绑定,返回指向带有 boost 的向量的指针