pass strings

Hello,

I have been trying to use a string I am reading in another function. It seems the string is not passed to following function.
To be clear here is my problem:

void read_string(string test){
test="prepeleac";
}
int main() {
string sir;
read_string(sir);
cout<<sir <<endl;
return 0;
}

Nothing get's printed as sir is not passed. DO you know how I can get it right? pass the string or alternative solutions?


Thanks,

Bogdan

@mirauta

For one, you have read_string as void, meaning it doesn't pass anything back. Two, even if you had it as string read_string(string test), you're not passing anything back to main. Remember, variables are forgotten when leaving a function. Here is your program, with corrections, to pass the string and receive it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

using namespace std;

string read_string()
{
string test ="prepeleac";
return test;
}

int main() 
{
string sir = "start";
cout << "SIR starts out as : '" << sir << "'" << endl;
sir = read_string();
cout << "and becomes '" << sir << "', after return from function." << endl << endl;
return 0;
}
Hello whitenite,

Thanks for the answer.

The problem is that I don't want to have read_string return a string.
I want to put the string value in "sir" like I can do with normal pointers.

I didn't want to return a string because I was reading several strings in the same function. Finally I returned a string*.
mirauta, please use [code]int i=5; // comment [/code] tags.
Anyway, you could use references instead of pointers when passing the parameter:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

void read_string(std::string &to)
{
  to = "test";
}

int main()
{
   std::string s = "This should be changed.";
   
   read_string(s);
   std::cout << s << std::endl;
}

You can pass string object by reference if you will declare your function as

void read_string(string &test);
Last edited on
Topic archived. No new replies allowed.