How to pass string by reference in C++

2 Answers

0 votes
#include <iostream>

void f(std::string &str) {
    str[0] = 'F';
    
    str[5] = 'W';
}
int main()
{
    std::string str = "C++ Programming";
    
    f(str);
    
    std::cout << str;
}




/*
run:

F++ PWogramming

*/

 



answered Aug 22, 2022 by avibootz
0 votes
#include <iostream>

void f(std::string &str) {
    str = "C Pro";
}
int main()
{
    std::string str = "C++ Programming";
    
    f(str);
    
    std::cout << str;
}




/*
run:

C Pro

*/

 



answered Aug 22, 2022 by avibootz

Related questions

1 answer 94 views
94 views asked Dec 19, 2024 by avibootz
1 answer 124 views
1 answer 207 views
1 answer 181 views
1 answer 155 views
...