【发布时间】:2015-11-22 09:47:35
【问题描述】:
我正在尝试使用 C++ 中的 Stack 来反转字符串中包含的单词的顺序,但我在最终输出中的字符串开头出现空格。
请帮我找出错误并解决它。
这是我的代码:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
int number;
cin >> number; // number of strings to reverse
for(int i = 0; i <= number; i++)
{
string str;
getline(cin, str); // input
std::stack<std::string> s; //stack
string str1 = "";
for(int i = 0; i <= str.length(); i++)
{
if(str[i] == ' ' || str[i] == '\0')
{ // add the word whenever it encounters a space
s.push(str1); //push the string
str1 = "";
}
else
str1 += str[i];
}
while(!s.empty())
{ // output
cout << s.top(); // simple displaying without space
cout << " ";
s.pop();
}
}
cout << '\n';
}
输入:
2
Reverse this String
OOP and DS
输出:
String this Reverse
DS and OOP
预期输出:
String this Reverse
DS and OOP
【问题讨论】:
-
我找到了。可以通过修复代码来解决
-
我应该怎么做? @Creris
-
您可以使用
std::stringstream line(str);省去一些解析麻烦,然后使用line >> str1;来获取单词。 -
您还可以通过使用调试器并单步执行代码来找到错误。
-
cin >> number;读入一个数字。但要获得该号码,您必须按 Enter。该输入将立即满足getline(cin, str);