1

I'm attempting to do something like this.

class testClass {        
  public:              
    void testFunction(char charArray[])
    {
    char output[].append(charArray.at(1));
    char output[].append(charArray.at(7));
    char output[].append(charArray.at(3));
    cout << output;
    }


int main() {
  testClass testObject;
  testObject.testFunction("Flowers"); 
  return 0;
}
   


}

What it's meant to do is:

  • get the Letters 'F', 'S' and 'O' from the char array from an index number
  • append that char to the output chararray

It's been frustrating since I've went from strings, to *chars, and char arrays.

Not really sure what the simpliest easiest solution is. Yes, I want to retain 1 char at a time from that string. It was just meant to be a fun project but it's way more complicated than I thought it'd be


expected output:

  • FSO
Intro verb
  • 13
  • 3

1 Answers1

1

Do you mean like this:

#include <string>
#include <iostream>

class testClass {        
  public:              
    void testFunction(const std::string& charArray)
    {
    std::string output;
    output.push_back(charArray.at(0));
    output.push_back(charArray.at(6));
    output.push_back(charArray.at(2));
    std::cout << output;
    }
};

int main() {
  testClass testObject;
  testObject.testFunction("Flowers"); 
  return 0;
}
   

Of course C++ like any sane language uses zero-based indexes.

Quimby
  • 17,735
  • 4
  • 35
  • 55
  • Thank you, I was pulling my hair out over this. :/ in what way does string& differ from string? is it some type of pointer? – Intro verb Jul 02 '21 at 21:05
  • No problem, I can explain some parts in more detail if you need, or if there was anything in particular that was tripping you up. – Quimby Jul 02 '21 at 21:07
  • @TedLyngmo I can't yet. but I'm going too. – Intro verb Jul 02 '21 at 21:07
  • @Quimby I'm unsure what the string& means exactly. is it some type of pointer? – Intro verb Jul 02 '21 at 21:08
  • @Introverb It is a reference to a string, yes it is similar to a pointer. See answers e.g. [here](https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in). It is used here to prevent making an extra copy of the string parameter because all parameters are copied/moved by default, C++ does not have implicit reference semantics for classes like Java does. IF you are learning C++, I can recommend a curated [list of recommended books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Quimby Jul 02 '21 at 21:09