首页 > 解决方案 > 一个变量的输入值也被保存到另一个变量中

问题描述

在下面关于称为get_array()问题的方法的代码中,由于capacity变量在用户在控制台中首次输入后更改为,并且capacity值分配给用户给出的值

我不确定发生了什么,但这让我很恼火,还是我错过了一些基本知识?请帮忙

#软件

我正在使用CodeBlocks v17.12

#操作系统

Windows 10 家庭版

#include <iostream>

using namespace std;

class LinearSearch
{
    int my_arr[];
    int capacity, c, val;

public:
    LinearSearch()
    {
        this->capacity = 0;
        this->c = 0;
        this->val = 0;

    }
    void get_array()
    {
        cout << "Define number of elements in the array: ";
        cin >> this->capacity;

        for( int i = 0; i < this->capacity; i++ )
        {
            cout << "Enter value " << i+1 << " - " << this->capacity << " : ";
            cin >> this->my_arr[i];
        }

        for( int k = 0; k < capacity; k++ )
        {
            cout << my_arr[k] << endl;
        }

        cout << endl;
    }

    void search_value()
    {
        cout << endl << "Enter a value to search: ";
        cin >> this->val;

        for(int j = 0; j < capacity; j++)
        {
            if(my_arr[j]==val)
            {
                cout << endl << this->val << " value found in the array at index array[" << j << "] value number " << j+1 << "." << endl << endl;
                c++;
                break;
            }
        }

        if(this->c==0)
            cout<<endl<<this->val<<" value not found in the array."<<endl<<endl;
     }
};

int main()
{
    int choice;
    LinearSearch obj;

    while( true )
    {
        cout << "0) Exit\n1) Insert Data\n2) Search Data\n\nEnter Option: ";
        cin >> choice;

        switch( choice )
        {
        case 0:
            return 0;
        case 1:

            obj.get_array();

            break;
        case 2:

            obj.search_value();

            break;
        default:
            cout << "\nWrong Option!!\n\n";
            break;
        }
    }

    return 0;
}


标签: c++arrays

解决方案


int my_arr[];不是有效的标准 C++,即使在 C 中,它也只能作为所谓的灵活数组成员出现在成员列表的末尾。

你应该std::vector<int> my_arr;改用。(需要#include<vector>。)

然后,您可以使用 向其中添加新元素,也my_arr.push_back(/*some number here*/);可以使用 调整数组的大小my_arr.resize(/*new size here*/);


推荐阅读