使用用户定义函数的字符串反转
String Reverse using user defined functions
我试图使用堆栈反转字符串,但问题是我自己定义函数,而不使用库。这是代码:
const int size = 50;
int top = -1;
char C[size];
int i = 0;
void push(int x){
top++;
if (top > size)
cout << "Error: Stackoverflow" << endl;
else
C[top] = x;
}
bool isEmpty() {
if (top < 0)
return true;
else
return false;
}
bool isFull() {
if (top > size)
return true;
else
return false;
}
void pop() {
if (isEmpty())
cout << "Error: The stack is empty!" << endl;
else
top--;
}
int Top() {
return C[top];
}
void Reverse(char *C, int n) {
// For Push
for (i = 0; i < n; i++)
push(C[i]);
// For pop
for(i = 0; i < n; i++) {
C[i] = Top();
pop();
}
}
int main() {
cout << "Enter the string: ";
cin >> C;
Reverse(C, strlen(C));
cout << "The reversed string is: " << C;
return 0;
}
现在,根据代码,字符串应该被反转,但我得到了以下输出:
Enter the string: Hi
The reversed string is: ii
我很确定push((做得很好,但我想pop((有问题吗?
字符串和堆栈都使用相同的数组,因此在C[i] = Top();
中,您将替换最后一个字符中的第一个字符,从而丢失它。
#include <iostream>
#include <string.h>
using namespace std;
const int size = 50;
int top = -1;
char C[size];
char stack[size];
int i = 0;
void push(int x)
{
top++;
if (top > size)
{
cout << "Error: Stackoverflow" << endl;
}
else
{
stack[top] = x;
}
}
bool isEmpty()
{
if (top < 0)
{
return true;
}
else
{
return false;
}
}
bool isFull()
{
if (top > size)
{
return true;
}
else
{
return false;
}
}
void pop()
{
if (isEmpty())
{
cout << "Error: The stack is empty!" << endl;
}
else
{
top--;
}
}
int Top()
{
return stack[top];
}
void Reverse(char *C, int n)
{
// For Push
for (i = 0; i < n; i++)
{
push(C[i]);
}
// For pop
for (i = 0; i < n; i++)
{
C[i] = Top();
pop();
}
}
int main()
{
cout << "Enter the string: ";
cin >> C;
Reverse(C, strlen(C));
cout << "The reversed string is: " << C;
return 0;
}
相关文章:
- 字符串函数在目标C++上运行时C++返回空
- 字符串函数返回奇怪的值
- 这里的字符串函数是什么意思
- 在字符串函数中抛出'char const*'实例后调用的终止
- 为什么 stl 字符串C++函数有时出错有时会出错?
- 从C++为字符串函数设置_ENV
- 来自 2D 数组的字符串函数
- 返回最长的公共子字符串函数 c ++
- 使用getline和字符串函数C++程序中的分段错误
- 在字符串函数的指针中返回地址
- 字符串函数:strcat()
- 这个子字符串函数有什么问题
- 字符串函数不返回字符串? C++
- 使用向量和字符串函数返回字符串
- 尝试修复一个字符串函数,该函数采用字符串并通过替换一些单词来更改它
- 逐字读取字符数组,无需字符串函数
- 我从我的字符串函数返回到主函数
- 为什么我不能从字符串函数返回字符串数组?
- 如何在不使用字符串函数的情况下在char数组中找到字符串?(C )
- 带有 #include< iostream.h> 的程序允许使用 strlen() 等字符串函数。为什么?