RangerFox
RangerFox

Reputation: 15

How to ask for integer input from the user until he enters blank line in C++?

So I need to store user inputs in a vector until he entersa blank line (or an invalid input). I've tried to convert the input to string, then compare it to a blank line, but it didn't work. Here's the code:

int input;
vector<int> v;
do
{
    cout << "Write a number!" << endl;
    cin >> input;
    v.push_back(input);
} while (to_string(input) != "");

Is there any way to do that?

UPDATE

Thank you guys so much for your help! The second answer solved all of my problems and the first one helped me to understand the logical background of it.

Upvotes: 1

Views: 1703

Answers (2)

Yksisarvinen
Yksisarvinen

Reputation: 22354

You can reverse your logic: instead of reading integers until something, you can read strings, check if they are empty and then convert them to integers.

std::string input;
std::vector<int> v;
std::getline(std::cin, input);
while(!input.empty())
{
    int number = std::stoi(input);
    v.push_back(number);
    std::getline(std::cin, input);
}

Notice that std::cin will not work, because it ignores whitespace (including newline character). Also, mixing std:: cin >> with std::getline is a bad idea

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

Use standard function std::getline. Here is a demonstrative program

#include <iostream>
#include <string>
#include <vector>

int main() 
{
    std::vector<int> v;

    while ( true )
    {
        std::cout << "Enter a number (Enter - exit): ";
        std::string line;

        if ( not std::getline( std::cin, line ) or line.empty() ) break;

        try
        {
            int value = std::stoi( line );
            v.push_back( value );
        }
        catch ( ... )
        {
            std::cout << "Not an integer number\n";
        }           
    }

    for ( const auto &item : v ) std::cout << item << ' ';
    std::cout << '\n';

    return 0;
}

Its output might look like

Enter a number (Enter - exit): 1
Enter a number (Enter - exit): 2
Enter a number (Enter - exit): 3
Enter a number (Enter - exit): A
Not an integer number
Enter a number (Enter - exit): 4
Enter a number (Enter - exit): 5
Enter a number (Enter - exit): 
1 2 3 4 5

Upvotes: 0

Related Questions