首页 > 解决方案 > 如何从 void 函数输出字符串?

问题描述

我创建了一个 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<<' (操作数类型为 'std::basic_ostream' 和 'void')

标签: c++functionvoid

解决方案


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

推荐阅读