string stream global variables?

Hi guys,

just wondering and this seems odd to me how come you can only use local variables with string stream and not global?

how is this even possible to allow an object or function to only accept locally defined variables or objects themselfs?

for example I have personAge and name globals but I can't pass them to the string stream instead I have to take an extra step and copy the values of my globals to locals of the function where the string stream is,

thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
  #include <iostream>
#include "person.H"
#include <sstream>

using namespace std;

Person:: Person(string n){

	personAge = 25;
	name = n;
	cout << "I am a person named " << name << endl;
}

void Person:: sayHi(){

  cout << "hi" << endl;
}

int Person:: age(int age){

	cout << age << endl;
	return age;
}

void Person:: printInfo(){

     stringstream stream;

     int localAge = personAge;
     string localName = name;

     stream << "name is ";
     stream <<  localName;
     stream << "age is ";
     stream << localAge;
     cout << stream.str() << endl;
}
?

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <sstream>

int foo;

int main(){
    foo = 42;
    std::stringstream stream;
    stream << foo;
    std::cout << stream.str() << std::endl;
    return 0;
}
There is no reason you couldn’t use values from any scope with any kind of stream.

I suspect you aren’t actually asking about global variables, but class member variables.

Either way, crank up your compiler warnings and tell us what it says when it complains.
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
//#include "person.H"
#include <sstream>

using namespace std;
class Person{
private:
    int personAge; // <---
    string name;   // <---
    
public:
    Person(string n){
        
        personAge = 25;
        name = n;
        cout << "I am a person named " << name << endl;
    }
    
    void sayHi(){
        
        cout << "hi" << endl;
    }
    
    int Personage(int age){
        
        cout << age << endl;
        return age;
    }
    
    void printInfo(){
        
        stringstream stream;
        
        //int localAge = personAge; // <---
        //string localName = name;  // <---
        
        stream << "name is ";
        stream <<  name;        // <---
        stream << " age is ";
        stream << personAge;    // <---
        cout << stream.str() << endl;
    }
};

int main()
{
    Person p("Someone");
    
    p.printInfo();
    return 0;
}


I am a person named Someone
name is Someone age is 25
Program ended with exit code: 0
hi guys thanks for the replies much appreciated,

and yes I think I'm talking about class member variables not global

Topic archived. No new replies allowed.