【问题标题】:Reading a length of a string, then inverse/reverse the string读取字符串的长度,然后反转/反转字符串
【发布时间】:2012-12-04 08:26:12
【问题描述】:

基本上,我已经设法写了这个,并且我设法反转了一个单词!但是当我尝试反转包含 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;
 }

【问题讨论】:

  • 如果应该是 C++ 赋值,为什么还要使用 C 字符串?
  • 你为什么不用string?将char words[100] 更改为string words 并将x=strlen(words) 更改为x=words.length()
  • 另外,cin &gt;&gt; words 将在第一个空白字符处停止解析。你需要使用类似getline()的东西。

标签: c++ dev-c++


【解决方案1】:

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

cin&gt;&gt;words 更改为cin.getline(words, sizeof(words), '\n');

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

【讨论】:

  • 老兄,谢谢!你是救生员。我的讲师从来没有想过我这个“getline”的事情。还是谢谢!
【解决方案2】:

您可以使用std::string 代替C char 数组,也可以使用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());

【讨论】:

  • 代码中的问题在于 cin 运算符 >> 仅从流中读取一个单词。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多