简体   繁体   中英

How to accept user input as the length of a vector in C++

How do i use userinput to determine the length of a vector? When using std::cin the size of the vector is always set to one despite what number i input. Any help would be appreciated.

int main()
{
    std::cout << "How many students do you want to enter?\n";
    int numOfStudents{};
    std::cin >> numOfStudents;

    std::vector results{ std::size_t(numOfStudents) };

    for (int i{ 0 }; i <= numOfStudents; ++i)
    {
        std::cout << "Enter a name: \n";
        std::string name;
        std::cin >> results[i];
        
    }

On this line:

std::vector results{ std::size_t(numOfStudents) };

You have not specified the value_type of the vector , so the compiler is forced to do class-template-argument-deduction (CTAD) to figure out the type of results . It sees a single size_t variable in the brace-initializer, and decides that results is a std::vector<size_t> containing a single element whose value is numOfStudents , and hence it has a size of 1.

Since you don't have any values to use for CTAD, you need to do this instead:

std::vector<std::string> results{ std::size_t(numOfStudents) };

Which calls the single-argument constructor of vector that constructs the vector with count elements.

Note that using braces can still lead to issues when the constructor argument is convertible to the value_type , so you could do this to avoid those issues:

std::vector<std::string> results( std::size_t(numOfStudents) );

In this case, the cast to size_t is unnecessary.

std::vector<std::string> results( numOfStudents );

Also, note that your loop goes out of bounds. The loop condition should be this instead:

i < numOfStudents

you can enter the vector then resize it to numOfStudents beacuse initial size of vector is 0 like:-

std::vector<std:: string> result;

result.resize(numOfStudents);

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