使用堆栈反转字符串 [英] Reversing a string using stack

查看:246
本文介绍了使用堆栈反转字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我是C ++的初学者,我正在尝试使用C ++编写程序以使用C ++反转字符串,但是它带来了各种各样的问题.我不打算在代码本身中初始化字符串.

Hi,
I am a beginner in C++ and I was trying a program in C++ to reverse a string using C++ but its giving all sorts of problems. I don''t intend to initialize the string in the code itself.

#include <iostream>
#include <string>
#include <stack>
#include <cstring>

using namespace std;

int main()
{
    int i=0;
    string text;
    stack<char> s;
    cout<<"Enter a string: ";
    cin>>text;
    for(int i=0;i<text.length();i++)
    {
    //text.length takes only one word and doesn't count whitespaces.
        s.push(text[i]);
    }
    while(!s.empty())
    {
        cout<<s.top();
        s.pop();
    }



我尝试将此字符串转换为text.c_str(),然后将它们压入堆栈,但是自从我在此添加新内容后,我就在语法中犯了错误.



I tried converting this string into text.c_str() and then pushing each of them in the stack but I was erring somewhere in the syntax since I new in this. What would be the correct way to do this?

推荐答案

您不是必须先创建一个stack<char>实例吗?我什至不了解C ++,所以我在这里猜测:stack<char> s = new stack&lt;char&gt;();
或类似的东西.查一下.
请也回答我的问题,为什么您在不暗示实际发生什么错误的情况下继续发布问题.这是您最少可以做的,因为它会使我们更轻松地为您提供帮助.

干杯,


Manfred
Wouldn''t you have to create a stack<char> instance first? I''m not even ankle deep into C++, so I''m taking a guess here: stack<char> s = new stack&lt;char&gt;();
or something like that. Look it up.
Please answer my question also, why do you keep posting questions with no inidication of what error actually occurred. That is the least you could do as it would make it easier for us to help you.

Cheers,


Manfred


我不确定为什么要使用堆栈来打印反转的字符串.为什么不只向后迭代呢?

I''m not sure why you are using a stack to print out the reversed the string. Why not just iterate backwards?

for (int i=text.length()-1; i>=0; i--)


在您的程序中,如果我输入"my name is xyz",则cin仅使用一个单词,而字符串仅获取"my".

In your program cin only take one word for example if i type "my name is xyz" than the string only get "my".

getline(cin,text,''\n'') 


可能会解决您的问题.


may solve your problem.


这篇关于使用堆栈反转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆