0

基本上,我已经成功地写了这个,并且我成功地反转了一个单词!但是当我尝试反转包含 2 个或更多单词的字符串时,我无法获得输出。任何人都知道如何解决这个问题,或者一些提示?

 #include <iostream>

 using namespace std;

 int main()
 {
      char words[100];
      int x, i;

      cout<<"Enter message : ";
      cin>>words;

      x = strlen(words);
      //This two line is used to reverse the string
      for(i=x;i>0;i--)
         cout<<words[i-1]<<endl;

     system("pause");
     return 0;
 }
4

3 回答 3

2

问题不在于 char 数组与 std::string - 它与输入法有关。

更改cin>>wordscin.getline(words, sizeof(words), '\n');

我猜这个任务是一个习惯数组的任务,所以坚持使用 char 数组 - 否则,是的,std::string 是易于使用的方法。

于 2012-12-04T08:43:43.033 回答
1

您可以使用std::string代替 C 字符数组,也可以使用 string::reverse_iterator 以相反的顺序读取单词。要读取以空格分隔的多个单词,您需要使用 std::getline。

std::string words;
std::getline(std::cin, words, '\n'); //if you read multiple words separated by space

for (string::reverse_iterator iter = str.rbegin() ; iter != str.rend(); ++iter)
{
  std::cout << *iter;
}

或使用std::reverse

std::reverse(words.begin(), words.end());
于 2012-12-04T08:38:46.080 回答
0

使用cin.getline(words,99)insted ofcin>>words因为 cin>>words 只会将 char 数组获取到第一个空格。

于 2012-12-04T09:02:17.467 回答