【问题标题】:"cout<<count<<endl;" isn't printing anything“cout<<count<<endl;”没有打印任何东西
【发布时间】:2020-01-10 12:08:43
【问题描述】:

cout&lt;&lt;count&lt;&lt;endl;sould 根据条件提供输出,但它没有打印任何内容,导致此类结果的代码中的故障/错误/缺陷是什么? 这是我的第一个问题,如果我不能完全理解,请见谅。

我使用了以下代码,我无法理解这里发生了什么。这是一个简单的输入输出问题。输出为我们提供了有关匹配两个团队制服的信息。

#include <stdio.h>
#include <iostream>

using namespace std;

main(){
    int a;
    cin>>a;
    int **b;
    b=new int*[a];
    for (int i = 0; i < a; i++)
    {
        b[i]=new int[2];
        for (int j = 0; j <2 ; j++)
        {
            cin>>b[i][j];
        }
    }

    int count=0;
    for (int i = 0; i < a*(a-1); i++)
    {   for (int j = 0; j < a; j++)
            if (b[i][0]==b[j][1])
                count=count+1;
    }
    cout<<count<<endl;

    for (size_t i = 0; i < a; i++)
    {
        delete b[i];
    }
    delete b;

}

输入:

3
1 2
2 4
3 4

输出不包含任何内容

【问题讨论】:

  • 如果cout 根本不打印任何东西,那么您的程序可能被之前的分段错误中断了。想想您为b 分配的数组的大小以及您在中间循环中访问的b 的最大索引。如果a 的值足够大,会发生什么?此外,您的代码不是有效的 C++,因为 main 必须具有指定的返回类型 int。此外,几乎在所有情况下,您都应该在 C++ 中使用std::vectorstd::string,而不是手动分配数组。您在这里学习了一种糟糕/错误的编程风格。
  • 谢谢,我在错误的地方得到了它,我的代码中有一个超出范围的异常。其实我刚从java切换到c++,用c++编码已经很久了。
  • 对不起,如果我弄错了,但是像这样的代码经常被那些似乎比 C++ 学习更多 C 的学生发布在这里(例如分配数组而不是使用 std::vector),并且通常完全出局过时的工具,有时甚至是预标准化 C++ 编译器(其中 main 没有声明 int 返回类型可能是有效的)。我对 Java 了解不多,但从我在这里听到的情况来看,大多数看起来与 C++ 中的 Java 相似的东西实际上并非如此,并且会导致来自 Java 的程序员感到困惑。例如new应该只在特殊情况下使用。
  • 感谢您的帮助,我刚刚从 java 切换到 c++,因此在一些事情上苦苦挣扎。在这种情况下如何使用“std::string”和“std::vector”,以及我在哪里可以学习良好的编程风格(指南或教程或可以提供帮助的东西),您能否帮助我更多。跨度>

标签: c++ printing output missing-data


【解决方案1】:

当你应该使用delete[] 时,你使用了超出范围的数组和delete。代码中的注释:

#include <iostream> // use the correct headers
#include <cstddef>

// not recommended: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice 
using namespace std;

int main() {  // main must return int
    size_t a; // better type for an array size
    cin >> a;
    int** b;
    b = new int*[a];
    for(size_t i = 0; i < a; i++) {
        b[i] = new int[2];
        for(size_t j = 0; j < 2; j++) {
            cin >> b[i][j];
        }
    }

    int count = 0;
    std::cout << a * (a - 1) << "\n"; // will print 6 for the given input
    for(size_t i = 0; i < a * (a - 1); i++) {
        // i will be in the range [0, 5]
        for(size_t j = 0; j < a; j++)             
            if(b[i][0] == b[j][1]) count = count + 1;
              // ^ undefined behaviour
    }
    cout << count << endl;

    for(size_t i = 0; i < a; i++) {
        delete[] b[i]; // use delete[] when you've used new[]
    }
    delete[] b; // use delete[] when you've used new[]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    相关资源
    最近更新 更多