我遇到了一些单词颠倒的问题
i got some problems with words reverse
我正在做一些算法编程,但我对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;
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 文本文件中的单词链表
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 字数统计函数在将单词添加到一组唯一单词时遇到问题
- 在文本中查找半个单词"ABBA"的问题
- 单词之间的莫尔斯电码空格问题
- 菜鸟问题:试图审查向量中的特定单词
- 问题在字符串指针中存储单词
- Qt C++macOS问题。我正在使用函数 .find( "a word") 在多集中搜索单词,它适用于 Windows 但不适用于 mac
- 从微妙的问题中提取单词
- (C++) 打印字符数组字符串的单词时出现问题
- 多个单词的计数单词出现的问题
- 在 C++11 中计算字母和单词的双字母组合的 std::线程向量的问题
- 我遇到了一些单词颠倒的问题
- 解析格式化输入时划分单词时出现问题
- 视觉程序在C++中使用VECTORS删除不喜欢的单词?[这是PPP第4章中的"Try This"问题]