怎么将Stack st3(“100,200,350,4000,80,66”);
转换为栈的元素66 80 4000 350 200 100?
转换为栈的元素66 80 4000 350 200 100?
解决方案
100
用strtok将每个数字都提取出来存储,然后重载输出运算符进行输出
参考:
参考:
#include<iostream> using namespace std; typedef unsigned long Item; class Stack { public: Stack(char *str) { size = MAX; char buffer[64] = {0}, *p; strcpy(buffer, str); top = 0; pitems = new Item[MAX]; pitems[top++] = atol(strtok(buffer, ",")); while((p = strtok(NULL, ","))) pitems[top++] = atol(p); } friend ostream& operator<< (ostream & stream,Stack &st); private: enum {MAX = 10}; // 定义常量MAX Item * pitems; // 存储栈元素 int size; // 栈的大小 int top; // 栈顶元素的下标 }; ostream& operator<< (ostream &stream,Stack &st) { for(int i = st.top - 1; i >= 0; i--) stream << st.pitems[i] << " "; return stream; } int main(void) { Stack st3("100,200,350,4000,80,66"); cout << st3; }