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:
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>
usingnamespace 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;
}
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;
}