【问题标题】:Error: expected unqualified-id before '{' token { [closed]错误:“{”令牌{ [关闭]之前的预期不合格ID
【发布时间】:2018-10-17 07:28:42
【问题描述】:

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

错误:'{' 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;
}

【问题讨论】:

  • 尾随 ; int main(int argc, char *argv[]); - 删除它

标签: c++ command arguments line


【解决方案1】:

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

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

看这里:

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

在这里,编译器会这样说:

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

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

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

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

要么做这样的事情(大家强烈推荐)......

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...
}

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

亲切的问候,

鲁克斯。

【讨论】:

  • “在 C++ 中被视为新行”该语言不关心换行符。如果您愿意,可以将所有代码放在一行中。
  • @user463035818 不不不,我想说它在这些语言中被 处理 像换行符(换行符),因此,只有真正的换行符为了可读性而存在...
  • 这也是不正确的。我很欣赏你的回答,试图用不那么技术的术语来解释一些东西,但你需要小心不要弄错。 ; 不被视为换行符。
  • @user463035818 好的,我编辑了答案...
  • 它也不是“行尾”,; 与行的结束位置无关。考虑for(int i=0;i &lt; 0;i++) 换行符在哪里?我猜你的意思是说 ; 结束一个声明(尽管我不得不承认我什至不确定这是否正确;)
【解决方案2】:

正如@StoryTeller 所说:

int main(int argc, char *argv[]); 

这条线导致了问题。删除此行末尾的;。

【讨论】:

  • 所以我删除了最后的分号,我得到了比以前更多的错误,例如:error: printf not declared in scope, and error no match for: 'operator 和 d 'double') :/
  • 问题解决了吗?如果没有,您可以分享新的错误列表吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多