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

编译报错:无法将char*、std::ofstream转为char(*)[95]求助

解决C++ ASCII表代码的编译错误问题

咱们先拆解你遇到的编译错误,再一步步修复代码里的问题——其实核心是函数声明和调用不匹配,再加上一些语法小错误导致的。

一、先修正最明显的语法错误

你的代码里有一行完全不符合C++语法的声明:

int values[MAX_SiZE], int values);

这行不仅写错了MAX_SIZE的大小写(你定义的是MAX_SIZE,这里写成了MAX_SiZE),还出现了多余的逗号和括号。正确的变量声明应该是:

const int MAX_SIZE = 95;
char symbols[MAX_SIZE];
int values[MAX_SIZE];

二、修复函数参数不匹配的核心问题

1. 解决buildTable的参数错误

你声明的buildTable要求第一个参数是二维char数组(char [][MAX_SIZE]),但调用时传的是一维数组symbols,这就导致了“无法将char转换为char()[95]”的错误。

实际上你是要把ASCII字符存到一维数组里,所以buildTable的参数应该改成接收两个一维数组:

void buildTable(char symbols[], int values[], int size);

2. 解决printTable的参数错误

你声明的printTable第一个参数是二维char数组,但调用时传的是outputFile(std::ofstream对象),类型完全不匹配,这就是第二个错误的根源。

因为你需要把表输出到文件,所以printTable应该先接收输出流,再接收两个一维数组和大小(注意用引用传递输出流,避免不必要的拷贝):

void printTable(std::ofstream& out, char symbols[], int values[], int size);

三、补充缺失的函数实现

你的代码只声明了函数,但没有写函数体,编译时会出现链接错误,所以我们需要补充buildTable和printTable的实现逻辑——比如填充ASCII可打印字符(从32到126,共95个),再格式化输出到文件和控制台。

修复后的完整代码

#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>

const int MAX_SIZE = 95;

// 修正后的函数声明
void buildTable(char symbols[], int values[], int size);
void printTable(std::ofstream& out, char symbols[], int values[], int size);

int main () {
    char symbols[MAX_SIZE];
    int values[MAX_SIZE];
    
    std::ofstream outputFile;
    outputFile.open("ascii.log");
    
    if(outputFile.fail()) {
        std::cout << "Error opening file. \n";
        return 1;
    } else {
        buildTable(symbols, values, MAX_SIZE);
        printTable(outputFile, symbols, values, MAX_SIZE);
    }
    
    outputFile.close();
    return 0;
}

// 填充ASCII可打印字符(32到126)
void buildTable(char symbols[], int values[], int size) {
    for(int i = 0; i < size; ++i) {
        values[i] = 32 + i;
        symbols[i] = static_cast<char>(values[i]);
    }
}

// 格式化输出到文件和控制台
void printTable(std::ofstream& out, char symbols[], int values[], int size) {
    // 先输出到控制台
    std::cout << std::setw(10) << "ASCII值" << std::setw(10) << "字符" << "\n";
    std::cout << "------------------------\n";
    // 再输出到文件
    out << std::setw(10) << "ASCII值" << std::setw(10) << "字符" << "\n";
    out << "------------------------\n";
    
    for(int i = 0; i < size; ++i) {
        std::cout << std::setw(10) << values[i] << std::setw(10) << symbols[i] << "\n";
        out << std::setw(10) << values[i] << std::setw(10) << symbols[i] << "\n";
    }
}

错误总结

  • 第一个编译错误:把一维数组传给了期望二维数组的函数,修正buildTable的参数为一维数组即可解决。
  • 第二个编译错误:把输出流对象传给了期望二维数组的函数,修改printTable的参数列表,让它接收输出流作为第一个参数就好了。
  • 额外修复了变量声明的语法错误,补充了函数实现(否则会出现链接错误)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:19:35