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

C++动态二维数组赋值问题:控制台无输出及直方图实现求助

Troubleshooting No Output When Assigning to Dynamic 2D Array in C++ Shell

Hey there! Let's work through this problem you're facing with your grade histogram program. As a new C++ programmer, dealing with dynamic arrays and input handling can feel tricky at first—let's break down what might be going wrong and fix it together.

First, let's recap your setup: you're trying to collect user input grades, create a histogram using a dynamic 2D array to store grades and their occurrence counts, but when assigning values to that array in the C++ Shell, you're getting no console output at all.

Here's the code snippet you shared (note it's incomplete, but we can work with it):

#include <iostream>
#include <vector>
using namespace std;
void sortGradeBubble(vector<int> &);
int countDiffNumber(vector<int>, int);
int main() {
    int grade = 0;
    bool validGrade = true;
    vector<int> grades;
    // get grades from users
    do {...

Common Reasons for No Output

There are a few likely culprits here:

  • Stuck in Input Loop: If your do...while loop doesn't have a clear exit condition (like entering a sentinel value such as -1 to stop input), the program might be waiting for more input instead of moving to the array assignment and output steps.
  • Dynamic Array Mismanagement: If you're manually allocating a 2D array (like int** hist = new int*[size];), you might have a memory allocation error, out-of-bounds access, or forgot to initialize elements—this could cause the program to crash silently or skip execution of output code.
  • Missing Output Logic: It's possible you haven't yet added code to print the histogram, or the output statements are placed in a part of the code that never gets executed.

Fixed Example Code

Since you're already using vector (which is safer than raw dynamic arrays), let's adjust your approach to use a vector of pairs (to store grade + count) instead of a raw 2D array. This avoids memory leaks and makes the code easier to debug:

#include <iostream>
#include <vector>
#include <algorithm> // For sort() (alternative to bubble sort)
using namespace std;

// Your bubble sort function (kept as you intended)
void sortGradeBubble(vector<int> &grades) {
    int n = grades.size();
    for (int i = 0; i < n-1; i++) {
        for (int j = 0; j < n-i-1; j++) {
            if (grades[j] > grades[j+1]) {
                swap(grades[j], grades[j+1]);
            }
        }
    }
}

// Build histogram using vector pairs (grade + count)
vector<pair<int, int>> buildHistogram(vector<int> &grades) {
    vector<pair<int, int>> histogram;
    if (grades.empty()) return histogram;

    // Sort grades first (use your bubble sort or standard sort)
    sortGradeBubble(grades);
    // sort(grades.begin(), grades.end()); // Uncomment for faster standard sort

    int currentGrade = grades[0];
    int count = 1;

    for (size_t i = 1; i < grades.size(); i++) {
        if (grades[i] == currentGrade) {
            count++;
        } else {
            histogram.push_back({currentGrade, count});
            currentGrade = grades[i];
            count = 1;
        }
    }
    // Add the final grade entry
    histogram.push_back({currentGrade, count});
    return histogram;
}

int main() {
    int grade;
    vector<int> grades;

    cout << "Enter grades (enter -1 to finish input):\n";
    while (true) {
        cout << "Enter grade: ";
        cin >> grade;

        // Exit condition to break input loop
        if (grade == -1) break;

        // Validate grade is in a reasonable range (adjust as needed)
        if (grade >= 0 && grade <= 100) {
            grades.push_back(grade);
        } else {
            cout << "Invalid grade! Please enter 0-100, or -1 to exit.\n";
        }
    }

    if (grades.empty()) {
        cout << "No grades entered.\n";
        return 0;
    }

    // Build and print the histogram
    vector<pair<int, int>> histogram = buildHistogram(grades);
    cout << "\nGrade Histogram:\n";
    cout << "Grade | Count\n";
    cout << "-------------\n";
    for (auto &entry : histogram) {
        cout << "  " << entry.first << "  |  " << entry.second << "\n";
    }

    return 0;
}

Key Fixes & Explanations

  1. Clear Input Exit Condition: The loop stops when the user enters -1, so the program won't get stuck waiting for input indefinitely.
  2. Grade Validation: We check that grades are between 0-100 (adjust this range if your use case differs) to avoid invalid data cluttering your histogram.
  3. Safe Histogram Storage: Using vector<pair<int, int>> eliminates the need for raw dynamic arrays, so you don't have to worry about manual memory management or out-of-bounds errors.
  4. Explicit Output: We added clear code to print the histogram once it's built, ensuring you'll see output as long as valid grades are entered.

If you were set on using a raw dynamic 2D array, you'd first need to count the number of unique grades, allocate the array with that size, then fill it with grade-count pairs—but vector is almost always the better choice in C++ for dynamic data—it's safer and easier to maintain.

Give this adjusted code a try in the C++ Shell, and let me know if you run into any other snags!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:48:04