C++字符数组,将字符向后放置作为输出

C++ Character Array, Placing Characters Backwards as an Ouput

本文关键字:字符 输出 数组 C++      更新时间:2023-10-16

我需要这个作业的帮助,它来自新学习者的计算机编程课程。这是一个字符数组C++代码被破坏了,我必须修复它。除了,我已经坚持了很长时间了,我需要一些帮助。如果有人能帮我解决这个问题,那就太好了!谢谢!

#include"stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int main()
{
  string word[20];
  char inputword;
  int x;
  cout<<"Enter a word ";
  cin>>inputword;
  if(word[0] = 'a' || word[0] = 'e' || word[0] = 'i' ||
    word[0] = 'o' || word[0] = 'u')
      cout<<"Words that start with vowels are not easily translated to Pig Latin"<<endl;
  else
  {
    cout<<"In Pig Latin: ";
    while(word[x] != NULL)
    {
      cout<<word[x];
      ++x++;
    }
    cout<<word[0]<<"ay"<<endl;
  }
}

只是为了咧嘴笑,我修改了你的代码才能工作。 希望这有帮助。

#include"stdafx.h"
#include<iostream>
// #include<string>  // working w/char arrays, don't need std strings
#include <cstring> // include this file so we can use strlen (c-style strings)
using namespace std;
int main()
{
  char word[20];  // you're working with a char array (not string array)
  // char inputword; // you don't need a separate input data structure
  int x;
  cout<<"Enter a word ";
  cin>>word;  // input directly into the word array
  // use == to compare for equality, using = is assigning to word[0]
  if(word[0] == 'a' || word[0] == 'e' || word[0] == 'i' ||
    word[0] == 'o' || word[0] == 'u')
      cout<<"Words that start with vowels are not easily translated to Pig Latin"<<endl;
  else
  {
    cout<<"In Pig Latin: ";
    // get the size of the word:
    // x = strlen(word);
    // work backwards through the array and print each char:
    for(int i=strlen(word); i>=0; --i)
    {
      cout << word[i];
    }
    cout << "ay" << endl;
    // use the for loop shown above instead of this
    // while(word[x] != NULL)
    // {
    //   cout<<word[x];
    //   ++x++;
    // }
    // cout<<word[0]<<"ay"<<endl;
  }
}

所以首先要确定给定程序中的错误:

  1. 你需要一个 char 类型的数组,在给定的程序中,数组被声明为字符串类型,另一个不是数组的变量被声明为字符。所以你需要的是:

    char word[20];
    
  2. 接受输入时,需要使用声明的字符数组:

    cin>>word;
    
  3. ===是有区别的,后者用于比较,前者用于赋值。因此,如果您想比较a是否与b相同,那么您会做if(a==b)但如果您想将b的值放入a中,您将a = b。请务必注意if(a = b)如果ab都是有效变量,则始终为真。因此,您需要将 if 语句更改为:

    if(word[0] == 'a' || word[0] == 'e' || word[0] == 'i' || word[0] == 'o' || word[0] == 'u')
    
  4. 最后,要向后输出字符串,您只需从数组中的最后一个字符开始打印到第一个字符。要获取数组的最后一个索引,请使用 strlen 函数获取字符数组的长度,该长度将与最后一个索引相同:

    n = strlen(word);
    

    然后从那里倒退:

    while(n>=0)
    { cout<<word[n];
      n--;
    }
    

    这将以相反的顺序为您提供字符数组。