You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让C++打印函数同时实现打印与返回输出?代码报错求助

问题分析与修复方案

你的代码存在几个关键语法逻辑错误,导致无法正常运行,以下是问题说明和修复后的代码:

错误点说明

  • 字符串与整数直接拼接错误:"Number of Items: " + GetNumItemsInCart()中,GetNumItemsInCart()返回的整数类型无法直接和const char*类型的字符串字面量相加,这会触发指针偏移运算,导致内存访问错误或输出乱码。必须将整数转换为字符串后再拼接。
  • 字符串字面量跨行语法错误:代码中直接换行的字符串写法不符合C++语法规范,会导致编译失败,需用\n表示换行。
  • 拼写错误:"Shoppig Cart"中的Shoppig应为Shopping,避免输出内容有误。

修复后的代码

#include <string>
#include <iostream>
// 假设ShoppingCart类的其他成员(如cartItems、customerName等)已正确定义

std::string ShoppingCart::PrintTotal() {
    std::string total = "";
    int size = cartItems.size();
    if (size == 0) {
        total += "SHOPPING CART IS EMPTY\n";
    }
    else {
        total += "OUTPUT SHOPPING CART\n";
        total += customerName + "'s Shopping Cart - " + currentDate + "\n";
        // 使用std::to_string将整数转换为字符串后拼接
        total += "Number of Items: " + std::to_string(GetNumItemsInCart()) + "\n";
        total += "\n";
        for (int i = 0; i < size; ++i) {
            total += cartItems.at(i).PrintBookCost() + "\n";
        }
    }
    std::cout << total;
    return total;
}

兼容旧编译器的替代方案

如果你的编译器不支持C++11的std::to_string(),可以用std::ostringstream来完成字符串与整数的拼接:

#include <sstream>
// ...
std::ostringstream oss;
oss << "Number of Items: " << GetNumItemsInCart() << "\n";
total += oss.str();

内容的提问来源于stack exchange,提问作者Noah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:15:39