控制台应用程序c ++

jay*_*t55 0 c++ console

我是控制台应用程序的新手,非常感谢一些指点......

我已经创建了一个新的控制台应用程序(未完成但应该正常工作),我选择了win32控制台应用程序,然后选择了"空项目"

这是我的代码:

#include <iostream>

void main() {

struct dude { 
    string name; 
    int age; 
} about; 

about.name = "jason"; 
about.age = 4000; 
cout << about.name << " " << about.age << endl;
}
Run Code Online (Sandbox Code Playgroud)

我得到的以下错误是:

------ Build started: Project: Test, Configuration: Debug Win32 ------
Compiling...
codey.cpp
.\codey.cpp(6) : error C2146: syntax error : missing ';' before identifier 'name'
.\codey.cpp(6) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
.\codey.cpp(6) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
.\codey.cpp(10) : error C2039: 'name' : is not a member of 'main::dude'
        .\codey.cpp(5) : see declaration of 'main::dude'
.\codey.cpp(12) : error C2065: 'cout' : undeclared identifier
.\codey.cpp(12) : error C2039: 'name' : is not a member of 'main::dude'
        .\codey.cpp(5) : see declaration of 'main::dude'
.\codey.cpp(12) : error C2065: 'endl' : undeclared identifier
Build log was saved at "file://c:\Users\Jason\Documents\Visual Studio 2008\Projects\Test\Test\Debug\BuildLog.htm"
Test - 7 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何调试这个吗?我在这里做错了什么?


工作...

#include <iostream> 
#include <string> 

struct Dude { 
    std::string name; 
    int age; };

    int main(int i) 
    { 
        while(i<4000)
        {
            i++;
        using namespace std; 
        Dude jason = { "Jason", i }; 
        cout << jason.name << " is " << jason.age << " years old.\n"; 
        }

        return 0; 
    }
Run Code Online (Sandbox Code Playgroud)

谢谢大家的帮助:D

Joy*_*tta 6

正确的代码应如下所示:

#include <iostream>
#include <string> 
using namespace std;

struct dude {
  string name;
  int age;
};

int main() { 

  struct dude about;
  about.name = "jason";
  about.age = 4000;

  cout << about.name << " " << about.age << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

编辑:添加必要的包含,以便编译.此外,作为最佳实践,在函数之外移动类型定义.

  • 你的比我好多了.+1 (3认同)

小智 6

#include <iostream>
#include <string>

struct Dude {
  std::string name;
  int age;
};

int main() {
  using namespace std;
  Dude jason = { "Jason", 4000 };
  cout << jason.name << " is " << jason.age << " years old.\n";
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

没有特别的顺序:

  • 在函数之外定义类型
  • 名称类型一致(这里是"Dude")
  • 初始化对象时提供值
    • 我在这里使用了聚合初始化,当你编写一个构造函数(ctor)时,你将使用稍微不同的语法
  • C++ stdlib几乎完全在std命名空间中
    • 你可以放在using namespace std;功能范围,如果你愿意,而不是std::在该功能体内输入
  • C++ stdlib字符串类型来自<string>标头
  • main返回int

修复这些问题并不是真正的调试,你只需要学习正确的语法.确保你有一本好书(例如Koenig和Moo的Accelerated C++),一位优秀的老师不会受到伤害.