I am confused about the use of #include <string>
at the start of a program. For example, in the code below, I don't use #include <string>
but the function will still print out the string "Johnny's favorite number is" when it is run.
#include <iostream>
using namespace std;
void printVariable(int number){
cout << "Johnny's favorite number is" << number << endl
}
However, in this code below, it does contain #include <string>
.
#include <iostream>
#include <string>
using namespace std;
class Var{
public:
void setName(string x){
name = x;
}
string getName(){
return name;
}
private:
string name;
};
int main(){
Var Classy;
Classy.setName("Johnny Bravo");
cout << Classy.getName() << endl;
return 0;
}
Do I only use #include <string>
if a variable represents a string?
Do I only use
#include <string>
if a variable represents a string?
Yes.
Use #include <string>
when you use a variable that has type std::string
.
The code "text here"
, contrary to intuition, is not a std::string
; it is a string literal, and a C-style string, and a const char[10]
convertible to const char*
. Welcome to C++ with its legacy oddities.