dt3tc 发表于 2017-10-28 18:49:59

编写的C++程序有多余的输出

本帖最后由 dt3tc 于 2017-10-28 20:22 编辑

如图
#include <iostream>

struct car{
        char maker;
        int made_year;
};
int main(){
    using namespace std;
        cout<<" How many cars do you wish to catalog?";
        int quantity=0;
        cin>>quantity;
        cin.get();
        car a={0};
        for(int b=0;b<quantity;b++){
                cout<<"Car #"<<b+1<<":\n";
                cout<<" Please enter the make:";
                cin.get(a.maker,14);
                cin.get();
                cout<<"Please enter the year made:";
                cin>>a.made_year;
                cin.get();
        };
        cout<<"Here is your collection:\n";
        for(int b=0;b<=quantity;b++)cout<<a.made_year<<" "<<a.maker<<endl;
        cout<<"goodbye"<<endl;

return 0;
}

谢谢

BngThea 发表于 2017-10-28 18:50:00

dt3tc 发表于 2017-10-30 17:07
现在编译通过,但运行到最后仍然有多余的输出

最后的for循环条件<=改成<
这里越界了

BngThea 发表于 2017-10-28 21:35:33

动态数组请用new配合delete进行处理
car a={0};
改为
car * a[] = new car;
记得最后进行释放
delete [] a;

dt3tc 发表于 2017-10-30 16:31:18

BngThea 发表于 2017-10-28 21:35
动态数组请用new配合delete进行处理
car a={0};
改为


改过了编译报错
||=== Build: Debug in 1 (compiler: GNU GCC Compiler) ===|
D:\mxf\src\tmp\1\main.cpp||In function 'int main()':|
D:\mxf\src\tmp\1\main.cpp|13|error: initializer fails to determine size of 'a'|
D:\mxf\src\tmp\1\main.cpp|13|error: array must be initialized with a brace-enclosed initializer|
D:\mxf\src\tmp\1\main.cpp|26|warning: deleting array 'a'|
||=== Build failed: 2 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|
#include <iostream>

struct car{
      char maker;
      int made_year;
};
int main(){
    using namespace std;
      cout<<" How many cars do you wish to catalog?";
      int quantity=0;
      cin>>quantity;
      cin.get();
      car * a[] = new car;
      for(int b=0;b<quantity;b++){
                cout<<"Car #"<<b+1<<":\n";
                cout<<" Please enter the make:";
                cin.get(a->maker,14);
                cin.get();
                cout<<"Please enter the year made:";
                cin>>a->made_year;
                cin.get();
      };
      cout<<"Here is your collection:\n";
      for(int b=0;b<=quantity;b++)cout<<a->made_year<<" "<<a->maker<<endl;
      cout<<"goodbye2"<<endl;
      delete [] a;

return 0;
}

BngThea 发表于 2017-10-30 16:40:37

car * a[] = new car;
这句打错了,应该是
car * a = new car;

dt3tc 发表于 2017-10-30 17:07:09

BngThea 发表于 2017-10-30 16:40
car * a[] = new car;
这句打错了,应该是
car * a = new car;

现在编译通过,但运行到最后仍然有多余的输出
页: [1]
查看完整版本: 编写的C++程序有多余的输出