如何从void函数输出字符串

How do I output a string from a void function?

本文关键字:输出 字符串 函数 void      更新时间:2023-10-16

我制作了一个void函数,目前正试图输出通过它传递字符串变量的结果,但出现了这个错误,我不确定它意味着什么。我过去曾使用过这段代码来输出void函数,所以我不确定为什么这段代码不同。下面,在if循环中的行上,是错误源所在的行。

if(choice == 'r')
{
cout << "Edited text: " << replaceExclamation(a) << endl;
}

void replaceExclamation(string usrStr)
{
for(int i = 0; i < usrStr.length(); ++i )
{
if(usrStr.at(i) == '!')
{
usrStr.insert(i, ".");
}
}
}

///错误为:error:no match for'operator<lt;'(操作数类型为"std::basic_stream"answers"void"(

void表示函数不返回任何值。

因此,cout << "Edited text: " << replaceExclamation(a) << endl;是错误的。

要这样写,您必须更改函数以返回string值。

string replaceExclamation(string usrStr)
{
for(int i = 0; i < usrStr.length(); ++i )
{
if(usrStr.at(i) == '!')
{
usrStr.insert(i, ".");
}
}
return usrStr;
}

在代码中,修改应用于局部变量,不会反映在main中。使用pass-by-reference,如:

if(choice == 'r')
{
replaceExclamation(a); // Allow the variable to be modified before printing
cout << "Edited text: " << a << endl;
}

void replaceExclamation(string& usrStr ) // Pass parameter by reference
{
for(int i = 0; i < usrStr.length(); ++i )
{
if(usrStr.at(i) == '!')
{
usrStr.insert(i, ".");    
}
}
}