inhaler
inhaler

Reputation: 185

C++ - Checking if string is empty

I have really hard time to get this. If my input is empty, I mean "Enter button" (means empty string, whitespaces), how can I detect it using C++?.

#include <iostream>
#include <stack>
#include <map>
#include <string>
using namespace std;

int main()
{    
    string a;
    cin>>a;

    if(a.empty())
        cout<<"I";
    else
        cout<<"V";

    return 0;    
}

How can I print "I" if it is an empty string and how does it work?
Thanks in advance.

Upvotes: 2

Views: 14345

Answers (3)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

The formatted input functions, i.e., the operator>>() conventionally start off skipping whitespace. The input operator for std::string certainly does that. This is probably not what you want.

You can disable this behavior using the manipulator std::noskipws, e.g., using

if (std::cin >> std::noskipws >> a) {
     std::cout << (a.empty()? "a is empty": "a is non-empty") << '\n';
}

However, the whitespace will be left in the stream. You'll probably want to ignore() it. From the sounds of it, you really want to read a line of input and do something special if it only contains spaces:

if (std::getline(std::cin, a)) {
    std::cout << (std::any_of(a.begin(), a.end(),
                              [](unsigned char c){ return !std::isspace(c); })
                  ? "a contains non-space characters"
                  : "a contains only spaces") << '\n';
}

Upvotes: 2

mateudu
mateudu

Reputation: 108

If I have understood you correctly:

  1. If you want to check if provided string is empty, just use isspace() function. It checks whether the string is null, empty or white space.

  2. If you want to accept empty input, just use getline() function.

    std::string inputValue;
    std::getline (std::cin,name);
    cout << name;
    

    Function getline() accepts empty input by default.

Upvotes: 4

mattnewport
mattnewport

Reputation: 14057

If you want an empty input to be accepted you have to tell the input stream to not skip whitespace using the noskipws IO manipulator:

cin >> noskipws >> a;

Your code should then work as you want it to.

Upvotes: 2

Related Questions