【问题标题】:This program will compile but not run. Other programs run该程序将编译但不会运行。其他程序运行
【发布时间】:2014-10-27 21:12:20
【问题描述】:

所以,我使用的是 dev-C++。编译器工作正常,一个简单的 hello world 程序与大约十几个其他简单程序一起工作。这是我正在为课堂做的事情的进行中的工作。

对我来说,它可以编译,但它永远不会运行。它出什么问题了?

#include <iostream>
#include <vector>
#include <cstdlib>
#include <algorithm>
using namespace std;

void getNames(vector<string> &vectorName, int &last, string temp);

int main() {
    vector<string> names;
    string tmp;
    int last = 0;

    getNames(names, last, tmp);

    for(int j = 0; j < last; j++) {
        cout << names.at(j) << endl;
    }

    system("PAUSE");
    return EXIT_SUCCESS;
}

void getNames(vector<string> vectorName, int &last, string temp) {

    while (true) {
        cout << "Enter a name (quit to stop): ";
        cin >> temp;
    if (temp == "quit") break;
        vectorName.push_back(temp);
        last = vectorName.size();
    }
}

【问题讨论】:

  • 定义“从不运行”。如果手动运行呢?你看到任何错误吗?如果有,它们是什么?
  • 我看到的第一件事是getNames 定义的参数与您声明的参数不同(缺少&amp;
  • 在您的main 函数中的getNames 上放置一个断点,看看它是否到达那里。如果是,请按 F10 直到它停止工作,并让我们知道它在哪里停止工作

标签: c++


【解决方案1】:

程序应该无法链接,因为它找不到以下定义:

void getNames(vector<string> &vectorName, int &last, string temp);

那是因为您的定义中缺少 &amp;

void getNames(vector<string> vectorName, int &last, string temp){
                            ^^^^^^^^^^^

添加&amp;,它应该可以正常编译和运行。

【讨论】:

  • @Brayheim:你为什么还要使用前向声明?只需随机播放函数即可。
  • @Deduplicator 是的,这是上课用的,我的教授对函数原型很奇怪。
  • @Brayheim:好吧,如果你遇到一个坚持糟糕编码标准的糟糕厨师,那可能是很好的工作培训。
【解决方案2】:

首先您的getNames 声明和实现签名不完全相同。

void getNames(vector<string> &vectorName, int &last, string temp){
void getNames(vector<string> vectorName, int &last, string temp){

【讨论】:

  • 没关系,这是我的错误,以为他使用的是 C 字符串而不是 C++ 字符串。
最近更新 更多