2016-05-13 63 views
0

我需要此作业的帮助,它来自针对新学习者的计算机编程课程。这是一个字符数组C++代码被破坏,我必须修复它。除此之外,我现在已经停留很长时间了,我想要一些帮助。如果有人能帮我弄清楚这真的太棒了!谢谢!只是为了笑容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; 
 
    } 
 
}

+0

使用'=='在C++中测试相等性,'='表示赋值。 –

+0

1)它有什么问题,2)你到目前为止做了什么? – immibis

+0

你需要做很多改变。当在if()中使用'word []'时,它仍然是未定义的。另外,当你将它用作'char'时,'word []'的类型是'string'。 –

回答

0

,我修改了代码工作。希望这可以帮助。

#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; 
    } 
} 
+0

感谢您帮助我使用此代码。我没有听说过#include 或strlen! –

0

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

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

    char word[20]; 
    
  2. 当拍摄输入,您需要使用声明的字符数组:

    cin>>word; 
    
  3. ===之间的区别,后者是用于比较而前者用于分配。所以,如果你想比较a是否与b相同,那么你会做if(a==b),但如果你想把b的值放入a,你会做a = b。重要的是要注意,如果ab都是有效变量,则if(a = b)将始终为真。因此,你需要的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--; 
    } 
    

    这将以相反的顺序给你你的字符数组。

+0

感谢您向我解释代码!这非常有帮助! :d –

相关问题