【问题标题】:Using for loops to enter data into arrays使用 for 循环将数据输入数组
【发布时间】:2018-06-29 13:42:17
【问题描述】:

所以我有这个包含 .h 文件和 main.cpp 的 C++ 程序。在 .h 我有这个类:

class Plaza
{
public:

    int length;
    double x;
    double y;

    Plaza();
    ~Plaza();

};

在 main.cpp 中,我尝试使用 for 循环输入数据,并且我设法存储 int i = 0 状态的数据,但是当 i 增加时,没有输入的数据被存储到数组中.对于内部循环,我尝试输入j < n、j < n-1 和j < n+1,但它不起作用。如何存储所有数据并打印出来?

#include <iostream>
#include "Plaza.h"

using namespace std;

int main() {

    int n;
    Plaza *obj1;

    cout << "Enter limit number (N): ";
    cin >> n;

    obj1 = new Plaza[n];

    for (int i = 0; i < n; i++) {
        cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
        for (int j = 0; j < 1; j++) {
            cin >> obj1[j].length;
            cin >> obj1[j].x >> obj1[j].y;
        }
    }

    for (int i = 0; i < n; i++) {
        cout << i + 1 << ". " << obj1[i].x << " " << obj1[i].y << " Length=" << obj1[i].length;
    }

    delete[] obj1;
    system("pause");
    return 0;
}

这是我得到的印刷品:

【问题讨论】:

  • j 循环有什么用?你的输入循环应该和你的输出循环一样。
  • 我认为解决了问题,不需要J循环,谢谢建议:)
  • 这里根本不需要使用裸new。使用std::vector。

标签: c++ arrays class for-loop


【解决方案1】:
for (int i = 0; i < n; i++) {
    cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
    for (int j = 0; j < 1; j++) {
        cin >> obj1[j].length;
        cin >> obj1[j].x >> obj1[j].y;
    }
}

这是你的罪魁祸首。去掉内部的 for 循环(不是 cin 语句,只是 for... 行及其右括号)并用 obj[i] 替换 obj[j]。您目前正在反复写信给obj[0]。

【讨论】:

  • 感谢您的帮助,我会将您的答案标记为正确。
【解决方案2】:
for (int i = 0; i < n; i++) {
        cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;
        for (int j = 0; j < 1; j++) {
            cin >> obj1[j].length;
            cin >> obj1[j].x >> obj1[j].y;
        }
    }


为什么需要第二个for循环。如果检查j值,它总是0,所以只插入一个值。,
试试这个

for (int i = 0; i < n; i++) {
            cout << "Enter length, x and y for " << i + 1 << ". plaza: " << endl;

                cin >> obj1[i].length;
                cin >> obj1[i].x >> obj1[i].y;
           }
        }

【讨论】:

    猜你喜欢
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 2012-10-01
    • 2016-07-27
    • 2015-05-11
    相关资源
    最近更新 更多