首页 > 解决方案 > 错误:'{' token { 之前的预期 unqualified-id

问题描述

所以我一直在我的计算机科学课上研究命令行参数,我得到了这个:

错误:'{' token { { ^

我一直在试图弄清楚它有什么问题,但在我的第一个 int 语句之后出现错误,我无法理解?这是代码。任何指导将不胜感激!在编码方面,我几乎是个菜鸟。

#include <iostream>
#include <string>
#include <sstream> // for std::stringstream
#include <cstdlib> // for exit()

using namespace std;

double int_rate;
const double RULE72 = 72;
const double YDAYS = 365;
int main(int argc, char *argv[]);
{    
    printf("argc = %d", argc);

    double amount;
    double int_rate;
    int days;
    int years;

    cout << "What is the interest rate? ";

    cin >> int_rate;

    years = RULE72 / int_rate;

    cout << "Your money doubles in " << years << " years.";

    days = years * YDAYS;

    cout << "Your money doubles in " << days << " days." << endl;

    cout << "Amount you would like to see double. ";

    cin << amount;

    cout << "Money earned by day " << (amount * 2) / days << endl;

    return 0;
}

标签: c++commandargumentsline

解决方案


对这个问题的一个更明确的答案是添加一个分号 (" ;"),它在C++和许多其他语言中被视为语句结束除了\用于分割行的 的用法) ......和以这些“分号”结尾的函数名被视为函数声明......所以不要将它与你想要在这里做的函数定义混淆......

函数声明是没有主体的预定义函数骨架,必须在代码中的某处定义......否则编译器会抱怨函数没有主体......

看这里:

int main(int argc, char *argv[]); // <- Semicolon
{
    // Some useful and useless code here... (but not going to work anyway, so...)
}

在这里,编译器会说:

嘿,这个函数末尾有一个分号,我知道,它是一个函数声明......

当它到达下一行时,它就像:

咦!这个函数的名字在哪里,我知道我在上一行有一个分号,所以不可能是那个!

编译器最终给出了一个关于主体没有声明的错误......所以,你有两个选择......

要么做这样的事情(每个人都强烈推荐)......

int main(int argc, char *argv[]) // <- Semicolon removed
{
    // Some useful and useless code here...
}

或者:(不推荐,但不会造成任何问题)

int main(int argc, char *argv[]); // <- Semicolon! Meaning: Declaration!
int main(int argc, char *argv[])  // Compiler says : Oh its the body (definition) of the declaration I read in the previous line...
{
    // Some useful and useless code here...
}

注意:我确信编译器会向您指出是哪一行导致了错误,因此您应该自己尝试一些方法,因为学习自己可以获得比渴望答案更多的经验......

亲切的问候,

鲁克斯。


推荐阅读