Making a public string

I have a program with multiple functions and they both use a string that is the same. So, I was wondering how do I make a string public? I defined outside my int main and the other function.
By public I assume you mean global, since you have nothing about classes here. Or code for me to base an answer off. Make a variable global by defining it outside of main
You mean a global string? If you are going to use the string from multiple files you can declare the string with extern in the a header file that you can include if you want to use the string
extern const std::string GLOBAL_STRING;.
In one of the source files you define the string
const std::string GLOBAL_STRING = "Hello World!";.

If you are only using one file you can skip the extern declaration. If you want a mutable string just remove the const keyword.
Last edited on
Sorry I am late on this, but I do mean in the same file and an example would be:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
using namespace std;
string name;
void printStuff();

int main(){
    cin >> name;
    printStuff();
}
void printStuff(){
    cout << name << "is your name" << endl;
}

but when I compile this I get error string does not name a type
Your code compiles and runs just fine. Are you sure you compiled exactly the same code you posted?
Well I tried to an example, but I guess it didn't portray my problem. So I have a file with 2 functions which are both int's. I use a string in both (name) where in int main, it gets the user's name and in int battle, it displays it. This gave me the error above
Post code, please.
I took down the code
Last edited on
I took down the code
Last edited on
If you use std::string before using namespace std; you have to write std::string
THANK YOU, I never would have found that.
You could just do using std::string, and not the whole namespace
Topic archived. No new replies allowed.