我遇到了一些单词颠倒的问题

i got some problems with words reverse

本文关键字:问题 单词颠 遇到      更新时间:2023-10-16

我正在做一些算法编程,但我对getchar()这种方法非常困惑。以下是所需的问题:

  • 输入:Hello World我来了
  • 输出:Come I Here World Hello

我尝试使用getchar()来获取每个字符,并使用字符串变量来收集字符。当空间到来时,我使用stack将当前字符串变量推入堆栈,使字符串变量等于"。但无论我尝试什么,输出总是输出胡言乱语,我不知道怎么做。

这是代码:

#include<iostream>
#include<stack>
using namespace std;
stack<string> re;// the stack
int main()
{
 char a;// the char to get very single char that print 
 string temp=""; 
 string all="";
while(a=getchar()!='n')//if enter don't come
{
    if(a==(char)'32')//if the space come,push temp and reset the temp equals ""
    {
        re.push(temp);
        temp="";//so that i can collect a new word without last one
    }
    else
        temp+=a;//temp collects the char
}
while(!re.empty())//get every string from the stack
{
    if(re.size()==1)
    cout<<re.top();
    else
    cout<<re.top()<<" ";
    re.pop();   
}
return 0;
}
a = getchar() != 'n'

a将是0或1,这取决于接收到的字符是否为'n'。例如,它可以更改为:

a = getchar(), a != 'n'

另一种可能是:

(a = getchar()) != 'n'

你也没有把最后一个字压在一起。字符串all根本没有使用,因此我删除了它

问题注释中指出的另一个问题是,如果a是空格,则比较无效:(char)'32'不是空格字符,但' '是.

更正的代码(与问题相同的标识):

#include<iostream>
#include<stack>
using namespace std;
stack<string> re;// the stack
int main()
{
    char a;// the char to get very single char that print
    string temp = "";
    while ((a = getchar()) != 'n')//if enter don't come
    {
        if (a == ' ')//if the space come,push temp and reset the temp equals ""
        {
            re.push(temp);
            temp = "";//so that i can collect a new word without last one
        }
        else
            temp += a;//temp collects the char
    }
    if (!temp.empty())//if last word is not empty then push it to the stack
    {
        re.push(temp);
    }
    while (!re.empty())//get every string from the stack
    {
        if (re.size() == 1)
            cout << re.top();
        else
            cout << re.top() << " ";
        re.pop();
    }
    return 0;
}