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
3
  • 1
    Arrays of char don't have the functionality contained in std::string. The only thing a char array can do is set individual elements. Commented Jul 2, 2021 at 21:02
  • 1
    It's been frustrating since I've went from strings, to *chars, and char arrays. Yes, it would be, why did you do that? Commented Jul 2, 2021 at 21:03
  • Indenting may help you. It speaks volumes. Commented Jul 2, 2021 at 21:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, I was pulling my hair out over this. :/ in what way does string& differ from string? is it some type of pointer?
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.
@TedLyngmo I can't yet. but I'm going too.
@Quimby I'm unsure what the string& means exactly. is it some type of pointer?
@Introverb It is a reference to a string, yes it is similar to a pointer. See answers e.g. here. 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.