简体   繁体   中英

I am trying to input a value into my stack but it gives me an error

for when I input the number 2 into my variables it telkls me that it wasn t defined? eny help?

int plusThree(){

input 2 -> stack;

return stack;

}

Continuing from my comments, the first problem that jumps out is that you have int large1, int large2 declared as parameters to twoLargest() . When you place variables (not references and not pointers) in the parameter list, the function receives a local-copy of the variable that resides on the function-stack and any changes you make to the local copies will be lost when the function returns and the stack is destroyed (eg the function-stack memory is released for re-use)

In C++ you can pass references as parameters that allows the function to operate on the actual variables from the calling function instead of copies. So instead of int large1, int large2 , you want to make large1 and large2 references, eg int& large1, int& large2

The next error that jumps out is your attempt to pass array from main() to your function as int arr[] . In main() you declare std::vector<int> array; , so array has type std::vector<int> , not int[] . (which would require a size to not be an incomplete type) You also want to pass array as a reference to avoid a complete copy of array being made for the function -- and -- since array isn't changed in your function you should declare the reference as const telling the compiler it will not be changed in the function which allows the compiler to further optimize its use.

Putting it altogether, changing the function type to void since it returns no value and fixing your syntax and sign problem and making a proper initialization to the lowest value in the type-range since you are looking for a max value, you would have:

/* type of function is 'void' it does not return a value.
 * by passing references to large1 and large2 the function
 * will operate on the variable passed from main() instead
 * of local "copies" of the variables.
 */ 
void twoLargest(const std::vector<int>& arr, int& large1, int& large2)
{
    /* always initialize max variables to min of range to start */
    large1 = std::numeric_limits<int>::min();
    large2 = std::numeric_limits<int>::min();
    
    for (size_t i = 0; i < arr.size(); i++) {
        if (arr[i] > large1) {
            large2 = large1;
            large1 = arr[i];
        }
        else if (arr[i] > large2) {
            large2 = arr[i];
        }
    }
}

( note: if the values are all negative, initializing large1 and large2 to 0 will not work. You also need to #include <limits> for the max() and min() of type.)

In order to pass large1 and large2 as references to twoLargest() , the int variables that you pass must be declared in the calling function ( main() here). So you need to declare two int variables in main() that you will pass, eg int l1, l2 will do. Then you will call your function as:

    twoLargest (array, l1, l2);   /* call function and output results */

Other big issues, your program will exhibit Undefined Behavior if the user makes a mistake entering integer values. You must validate EVERY user-input. To do that you check the stream-state for std::cin after each input and BEFORE you attempt to make use of the variable filled by the input. It can be a simple as:

if (!(std::cin >> sizeArray)) {
    std::cerr << "error: invalid integer input.\n";
    return 1;
}

where you simply exit the program if the user provides an invalid sizeArray input. Or, you can do full error detection and recovery such as where you take values to fill the array. In that case, to handle any non-integer input you need to check the stream-state flags for .eof() and .bad() (which are unrecoverable errors) and .fail() which indicates a non-integer input, which you correct by clearing the failbit and removing the unread characters from stdin before allowing the user to try again. You can do that similar to:

    for (; i < sizeArray;) {   /* only increment on valid input */
        int n;
        std::cout << "array[" << i << "]: ";
        
        if (!(std::cin >> n)) {
            /* if eof() or bad() break read loop */
            if (std::cin.eof() || std::cin.bad()) {
                std::cerr << "(user canceled or unreconverable error)\n";
                return 1;
            }
            else if (std::cin.fail()) {     /* if failbit */
                std::cerr << "error: invalid integer input.\n";
                std::cin.clear();           /* clear failbit */
                /* extract any characters that remain unread */
                std::cin.ignore (std::numeric_limits<std::streamsize>::max(),
                                 '\n');
            }
        }
        else {  /* only on good input */
            array.push_back(n);
            i += 1;                         /* increment loop counter */
        }
    }

( note: i is declared before the loop is entered because it is used for multiple purposes in my example)

If you put it all together, you could have a example that finds the two largest that looks something like:

#include <iostream>
#include <vector>
#include <limits>

/* type of function is 'void' it does not return a value.
 * by passing references to large1 and large2 the function
 * will operate on the variable passed from main() instead
 * of local "copies" of the variables.
 */ 
void twoLargest(const std::vector<int>& arr, int& large1, int& large2)
{
    /* always initialize max variables to min of range to start */
    large1 = std::numeric_limits<int>::min();
    large2 = std::numeric_limits<int>::min();
    
    for (size_t i = 0; i < arr.size(); i++) {
        if (arr[i] > large1) {
            large2 = large1;
            large1 = arr[i];
        }
        else if (arr[i] > large2) {
            large2 = arr[i];
        }
    }
}

int main() {
    
    std::cout << "How large would you like the array to be?: ";
    int l1, l2, sizeArray, i = 0;   /* declare vars for large1/2 in main */
    /* validate EVERY user-input */
    if (!(std::cin >> sizeArray)) {
        std::cerr << "error: invalid integer input.\n";
        return 1;
    }
    
    std::vector<int> array;
    for (; i < sizeArray;) {   /* only increment on valid input */
        int n;
        std::cout << "array[" << i << "]: ";
        
        if (!(std::cin >> n)) {
            /* if eof() or bad() break read loop */
            if (std::cin.eof() || std::cin.bad()) {
                std::cerr << "(user canceled or unreconverable error)\n";
                return 1;
            }
            else if (std::cin.fail()) {     /* if failbit */
                std::cerr << "error: invalid integer input.\n";
                std::cin.clear();           /* clear failbit */
                /* extract any characters that remain unread */
                std::cin.ignore (std::numeric_limits<std::streamsize>::max(),
                                 '\n');
            }
        }
        else {  /* only on good input */
            array.push_back(n);
            i += 1;                         /* increment loop counter */
        }
    }
    
    i = 0;  /* flag controlling comma output */
    std::cout << "\nstd::vector<int>: ";
    for (const auto& n : array) {
        if (i) {
            std::cout.put(',');
        }
        std::cout << n;
        i = 1;
    }
    std::cout.put('\n');
    
    twoLargest (array, l1, l2);   /* call function and output results */
    
    std::cout << "\nresult twoLargest(): " << l1 << ", " << l2 << '\n';
}

Example Use/Output

$ ./bin/twoLargest
How large would you like the array to be?: 5
array[0]: foo
error: invalid integer input.
array[0]: 2
array[1]: 9
array[2]: 3
array[3]: Seven, I want to enter 7!
error: invalid integer input.
array[3]: 7
array[4]: 4

std::vector<int>: 2,9,3,7,4

result twoLargest(): 9, 7

There were a few more tips I noted in the comments. Other than correcting your parameter errors, the big takeaway is you need to validate EVERY user-input. After you write an input routine, go try and break it intentionally (users will enter bad input by mistake and intentionally to find vulnerabilities in your code). If your input routine breaks when you test it -- go fix it and try again until you are satisfied with it.

Look things over and let me know if you have further questions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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