【问题标题】:translating a string of words to another string of words将一串单词翻译成另一串单词
【发布时间】:2021-06-24 11:31:31
【问题描述】:

我想要一个程序,它获取 char[] 作为输入并输出相同长度的 char[] 但它的第一个字符是 w ,最后一个是 f 以及介于两者之间的所有字符是os。

如果输入的大小为 1,则输出应为 de 'w',如果有 2 个字符,则应为 wf

示例:“stackOverflow”=>“wooooooooooof”

  #include <iostream>
  #include <cstring>
  
  using namespace std;
 
  void translate(char human[], char dog[]); //human is input and dog is output
 
  int main()
  {
      char human[100], dog[100];
 
      cout << "Enter a string: ";
      cin.getline(human, 100);
 
      for (int i = 0; i < strlen(human); i++)
      {
          dog[i] = human[i];
      }
      dog[strlen(human)] = '\0';
 
      cout << dog << endl;
 
 
      return 0;
  }
 
 
  void translate (char human[], char dog[])
  {
      for (int i = 0; i < strlen(human); i++)
      {
          dog[i] = human[i];
      }
 
  }

【问题讨论】:

  • 程序编译,无论用户输入什么如“hello”,程序都会输出“hello”。我知道我缺少几个步骤来获得我想要创建的内容。它应该输出“wooof”而不是“hello”。
  • 你的代码甚至没有尝试做你期望它做的事情,而且你从不调用main中的translate 函数

标签: c++ arrays string function


【解决方案1】:

也许是这样的:

      for (int i = 0; i < strlen(human); i++)
      {
          if(i == 0)
          {
            dog[i] = 'w';
          }
          else if(i == (strlen(human)-1))
          {
            dog[i] = 'f';
          }
          else
          {
            dog[i] = 'o';
          }
      }

【讨论】:

  • 请注意,人类唯一有用的信息是字符串的长度
猜你喜欢
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多