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 87 views
87 views asked Dec 19, 2024 by avibootz
1 answer 116 views
1 answer 198 views
1 answer 175 views
1 answer 149 views
...