简体   繁体   English

在main函数中使用类中的数组

[英]Using array from class in main function

Consider the following code: 请考虑以下代码:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    class treasure
    {
    public:
        char name[100];
        double value[100];
        double weight[100];
    };

    int itemNumber, totalWeight, i;

    treasure item;

    std::cout << "Enter total item weight: " << std::endl;
    std::cin >> totalWeight;
    std::cout << "Enter total item number: " << std::endl;
    std::cin >> itemNumber;
    for( i = 0; i < itemNumber; i++)
    {
        std::cout << "Enter item name: " << std::endl;
        std::cin >> item.name[i];
    }

    return 0;
}

I wanted to input 5 item in the array but it is just asking for two item. 我想在数组中输入5个项目,但它只是要求两个项目。 It takes one item at first and then after printing three lines again takes another input. 它首先需要一个项目,然后在打印三行后再次输入另一个项目。 What seems to be the problem. 似乎是什么问题。 What did went wrong? 出了什么问题?

char name[100]; means that you can save up to 100 items of type char , not 100 strings. 意味着您最多可以保存100个char类型的项目,而不是100个字符串。

An important effect here is that your input is buffered. 这里一个重要的影响是你的输入是缓冲的。 std::cin >> item.name[i]; takes one char from the input buffer and writes it to name[i] . 从输入缓冲区中获取一个char并将其写入name[i] The rest of your input remains in the buffer and will be used for the next execution of cin , ie the next execution of the same code line. 其余的输入保留在缓冲区中,将用于下一次执行cin ,即下一次执行相同的代码行。

So if you enter eg 'abc' it saves 'a' to item.name[0] , 'b' to item.name[1] and 'c' to item.name[2] . 因此,如果输入例如'abc',则将'a'保存到item.name[0] ,将'b'保存到item.name[1] ,将'c'保存到item.name[2] For item.name[3] the input buffer is empty so it waits for your next input. 对于item.name[3] ,输入缓冲区为空,因此它等待您的下一个输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM