Search code examples
arraysc-stringspointer-to-member

Append, C-strings and struct member functions


How I can add what characters I want to the end of what the user would type in. Also a pointer is being passed into the wordArr[] if that helps at all

#include <iostream>
#include <string>
#include <cctype>

using namespace std;
struct Word {
    string english;
    string pigLatin;
};




void convertToPigLatin(Word wordArr[], int size){   //converts given word array into piglatin
    char a = 'a';
    char y = 'y';
    char begins;
    int i = 0;
    
    for(int index = 0; index < size; index++){
        wordArr->pigLatin[index] = wordArr->english[index];
    }
    
    
    for(int index = 0; index < size; index++){
        
        if(isspace(wordArr->english[index])){
            
            i = index - 1;
            wordArr->pigLatin.append(i, 'a');
            i++;
            wordArr->pigLatin.append(i, 'y');
            
        }
    }

I've tried moving around whats within the append parameters, I also tried doing the += operator to show hoping that it would take whatever i type then add ay to the end of it wordArr->pigLatin += "ay";but it adds it to the beginning and not at the end


Solution

  • Some hints:

    • using wordArr->.. means you're treating wordArr as if it is a pointer to a single Word object, not an array, which seems inconsistent with the naming. You want wordArr[i].... to access the ith element of the array.
    • wordArr->pigLatin[index] is accessing the index'th character in the string pigLatin which seems incorrect, unless size is actually the length of the strings, and not the size of the wordArr array (which seems more likely)
    • the method call pigLatin.append(i, 'a') will append i copies of the character 'a' to the end of the string. This seems unlikely to be what you actually want.

    Generally in C++ you want to avoid using C constructs like raw arrays and C-strings. You want to use std::string (which you are) and std::vector instead.