【发布时间】:2019-08-08 19:59:05
【问题描述】:
这是给我的任务。 我是一个刚开始编程的菜鸟。 字符串作为一个整体不会压入堆栈以及如何弹出它。
问题陈述:- 将一个由全名组成的整个字符串分割,将字符串分成3部分得到名字中间名和姓氏,并按照姓氏名字中间名的顺序显示它们仅使用堆栈。
我尝试过使用 2D 堆栈
#include<iostream>
#include<conio.h>
#include<stdio.h>
#include<string>
using namespace std;
using std :: string;
char s1[100];
char s2[50],s3[50],s4[50];
int i=0,j=0,k=0,max1=9,top=-1;
char stack[10][10];
char re[10];
void push(char val[])
{
if(top>=max1)
{
cout<<"Stack overflow";
}
else
{
top++;
int a=0;
for (int i=0;i<stack[top]['\0'];i++)
{
stack[top][a]=val[i];
a++;
}
}
}
char* pop()
{
if(top<0)
{
cout<<"Stack underflow";
}
else
{
//for(int j=0;j<=top)
for(int i=0;i<stack[top]['\0'];i++)
{
re[i]=stack[top][i];
top--;
return re;
}
}
}
void divstring()
{
for(i=0;s1[i]!=' ';i++)
{
s2[i]=s1[i];
}
s2[i]='\0';
i++;
while(s1[i]!=' ')
{
s3[j]=s1[i];
j++;
i++;
}
s3[j]='\0';
i++;
while(s1[i]!='\0')
{
s4[k]=s1[i];
k++;
i++;
}
s4[k]='\0';
i++;
}
int main()
{
//clrscr();
cout<<"Enter the string: ";
gets(s1);
divstring();
cout<<"The 1 part is "<<s2<<endl;
cout<<"The 2 part is "<<s3<<endl;
cout<<"The 3 part is "<<s4<<endl;
// getch();
push(s1);
push(s2);
push(s3);
cout<<pop();
return 1;
}
没有编译时错误,但字符串不会被压入堆栈或弹出。
【问题讨论】:
-
听起来你可能需要学习如何使用调试器来单步调试你的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs 和 Debugging Guide
-
你认为这个位在做什么?
stack[top]['\0'] -
无论哪一本 C++ 书籍告诉你使用
gets()——你需要再买一本 C++ 书籍。无论哪位教练告诉你使用它,你都需要换一个教练。 -
你为什么不用
std::stack? -
push(s1); push(s2); push(s3);应该是push(s2); push(s3); push(s4);吗?我猜s1太大了,不适合你的“堆栈”
标签: c++ string data-structures