I'm trying to concatenate strings using +, but there is some weird stuff going on. Here is my "Grade" class I have for a class project:
#pragma once #include <fstream> #include <iostream> #include <string> #include <vector> using namespace std; class Grade { private: string className; string student; string letter; public: Grade(string c, string s, string l) : className(c), student(s), letter(l) {} string getLetterGrade() const { return letter; } string getClassName() const { return className; } string getStudent() const { return student; } void setLetterGrade(string l) { letter = l; return;} void setClassName(string c) { className = c; return;} void setStudnet(string s) { student = s; return;} string toString() const { string output = "hello"+student; return output; } }; Obviously, the toString() method isn't currently what I want it to be. If I run the toString() as above, I get "hello529173860" out, as expected. However, if I change the line to:
string toString() const { string output = student+"hello"; return output; } then the output is "hello3860". This isn't just putting the hello string on the front, but its replacing characters from the student string in the process... somehow?
Furthermore, if I try to use:
string toString() const { string output = "hello"+" world"; return output; } I get an error:
Grade.h: In member function ‘std::string Grade::toString() const’: Grade.h:29:53: error: invalid operands of types ‘const char [6]’ and ‘const char [7]’ to binary ‘operator+’ string toString() const { string output = "hello"+" world"; return output; } ^ I'm really at a loss for what it going on here... especially since I have done string concatenation earlier in the program without issue. What I would like is to output something like:
"student+[some white space]+letter+[some white space]+className"
C-String(a simple string-literay, an array of characters, e.g. "hello") with a std::string. When you write"hello" + "world"you are actually trying to add two char arrays or two char* pointers. That said, the main problem is not the string operator +, it's somewhere else in your code. See ideone.com/wKrmu6Gradeobjects?std::string(const_char_one) + std::string(const_char_two)orstrcatif you're using C-style strings? Concating anstd::stringwith aconst char*will Do The Right Thing, but"hello" + "world"will not.strcatthough, I'd agree that it looks much more effective.