我觉得这是一个非常基本的问题,但是我已经在互联网上搜索了一个多小时,但没有找到答案。
我正在编写一个将输入作为字符串的文本接口。如果输入字符串是数字,我想将字符串转换为整数并将其压入我创建的堆栈中。
文本界面的代码如下:
#include <iostream>
#include "textInterface.h"
#include "Stack.h"
#include <string>
#include <regex>
using namespace std;
void Interface(){
Stack stack = Stack();
string input;
cout << "Please enter a number or operation";
cin >> input;
if (input == "."){
cout << stack.pop();
} //this pops the stack
if (input == "+"){
int a = stack.pop();
int b = stack.pop();
int c = a + b;
stack.push(c);
} //pops the first two things off the stack, adds them, and pushes the result
if (input == "-"){
int a = stack.pop();
int b = stack.pop();
int c = a - b;
stack.push(c);
} //pops the first two things off the stack, subtracts them, and pushes the result
if (input == "*"){
int a = stack.pop();
int b = stack.pop();
int c = a * b;
stack.push(c);
} //pops the first two things off the stack, multiplies them, and pushes the result
if (input == ".s"){
cout << stack.count();
} //returns the size of the stack
if (regex_match(input, "[0-9]")){
int num;
stringstream convert(input);
convert >> num;
stack.push(num);
} //This is the part with the error!!!
}
就像我说的,我想检查输入是否为数字,如果是,则将字符串转换为int并将其压入堆栈。我以前使用过正则表达式,但是已经有一段时间了,并且它在Python中使用(我对C ++还是陌生的)。我知道我的regex_match格式不正确,是否有人对如何使其正确无任何建议,或者有阅读资源的建议?
不要检查它是否看起来像整数,然后将其转换为整数。而是将其转换为整数,看看是否可行。使用std::stoi
(或,stol
或stoll
,取决于您期望数字的大小。)(英寸<string>
):请参见此处。
如果无法将字符串转换为指定大小的整数,则会引发异常,因此您必须在内执行该函数try
。(如果您是pythonista,则应熟悉该样式。)
另外,如果有一个数字但没有占用整个字符串(即结尾的垃圾),则size_t
指向第二个参数的指针将设置为第一个未使用字符的索引,因此如果要检查整个数字string是一个数字,您还应该检查以确保返回的索引是输入字符串的大小。
如果您对异常不满意,即使是标准库抛出的异常,也可以只使用基础的标准c函数strtol
和好友。它们具有相似的接口,但是使用结合设置的任意值返回errno
来尝试通信失败。就我个人而言,我认为异常接口不太友好,但与往常一样,口味也有所不同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句