Str->int

C++里string转int常见有atoi和stoi。头文件都是#include

atoi()的参数是const char*, 所以对一个字符串要先c_str()把string转换成const char类型,而stoi()的参数是const string,可直接使用。

#include<cstring>

string str;
int a = atoi(str.c_str());
int b = stor(str);

atoi不会做超出范围的检查,超出上界输出上界,超出下界输出下界。
stoi会做超界检查,超出范围报running time error。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
代码如下: ``` #include <iostream> #include <string> #include <math.h> using namespace std; template<class T> class vlist // 线性表抽象类 { public: virtual void in(T &e) = 0; virtual T out() = 0; }; template<class T> class Element // 线性表存储元素 { public: T data; Element<T>* next; Element() { next = NULL; } }; template<class T> class SStack : public vlist<T> // 栈的实现类 { private: Element<T>* top; // 栈顶元素指针 public: SStack() { top = NULL; } void in(T &e) // 入栈操作 { Element<T>* p = new Element<T>; p->data = e; p->next = top; top = p; } T out() // 出栈操作 { if (top == NULL) // 栈空,抛出异常 throw "Stack is empty!"; Element<T>* p = top; top = top->next; T temp = p->data; delete p; return temp; } }; template<class T> class Quene : public vlist<T> // 队列的实现类 { private: Element<T>* front; // 队头元素指针 Element<T>* rear; // 队尾元素指针 public: Quene() { front = rear = NULL; } void in(T &e) // 入队列操作 { Element<T>* p = new Element<T>; p->data = e; p->next = NULL; if (front == NULL) front = rear = p; else { rear->next = p; rear = p; } } T out() // 出队列操作 { if (front == NULL) // 队空,抛出异常 throw "Quene is empty!"; Element<T>* p = front; front = front->next; T temp = p->data; delete p; return temp; } }; int main() { vlist<int>* intp; vlist<string>* strp; SStack<int> ints; Quene<int> intq; SStack<string> strs; Quene<string> strq; intp = &ints; int t = 2; intp->in(t); t = 3; intp->in(t); t = 4; intp->in(t); for (int i = 0; i < 3; i++) cout << intp->out() << " "; intp = &intq; t = 2; intp->in(t); t = 3; intp->in(t); t = 4; intp->in(t); for (int i = 0; i < 3; i++) cout << intp->out() << " "; strp = &strs; string str; cout << endl; for (int i = 0; i < 3; i++) { cin >> str; strp->in(str); } for (int i = 0; i < 3; i++) cout << strp->out() << " "; cout << endl; strp = &strq; for (int i = 0; i < 3; i++) { cin >> str; strp->in(str); } for (int i = 0; i < 3; i++) cout << strp->out() << " "; } ``` 这段代码定义了一个 vlist 抽象类,并且定义了两个线性表的实现类:SStack 和 Quene,分别实现了栈和队列的基本操作。在 main 函数中,分别使用了栈和队列的实现类,演示了它们的基本操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值