c++ - 如何从 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')
解决方案
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;
}
推荐阅读
- c# - 使用队列在两个 BackgroundWorker 之间传递数据
- validation - 如何检查codeigniter 3的mysql表中是否存在电子邮件ID,手机号码,姓名和出生日期的组合
- excel - 忽略或删除数据连接中的线路
- xamarin.ios - 如何在 Xamarin IOS Live Camera 中添加 OverlayView
- r - prcomp "colMeans(x, na.rm = TRUE) 中的错误:'x' 必须是数字"
- c# - 如何在.cshtml文件中以调试和发布模式声明变量
- angular - Observables 数组请求一个字符串?
- hibernate - HQL 查询返回单个最新记录,但查看两个(不是一个)日期列
- ios - 有没有办法确定 UILabel 中的文本结束坐标?(不是标签框矩形)
- java - 是否可以根据 @Autowire 的路径变量来决定使用哪个 bean?