0

Here's what I have:

#include <iostream>
using namespace std;

int main() {
    string name;
    cout << "Customer name: ";
    cin >> name;

    if (name != "") {
    //stuff omitted
    } else if (name.empty()) {
           cout << "You must enter a customer name.";
    }

return 0;
}

As shown, I want to be able to accept an empty string to output an error when an empty string is inputted. The problem is that the program does not take an empty string; the terminal simply waits for input if I hit enter without typing anything, so the error message is never triggered. How do I make the program take an empty string?

3ggz
  • 1
  • Does this answer your question? [C++: how do I check if the cin buffer is empty?](https://stackoverflow.com/questions/4999650/c-how-do-i-check-if-the-cin-buffer-is-empty) – ChrisMM Apr 07 '22 at 01:29
  • I found an answer: use cin.ignore(); getline(cin, varname); – 3ggz Apr 07 '22 at 01:30
  • 1
    Warning: If you `ignore` in front of a `getline` you run a serious risk of finding a case where you reach that `getline` without data in the stream that you want ignored. The best place to put an `ignore` is after IO operations that leave unwanted data in the stream. This has the added advantage of keeping cause and effect close together.\ – user4581301 Apr 07 '22 at 01:34

1 Answers1

2

Try this:

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

int main() {
    string name;
    cout << "Customer name: ";
    getline(std::cin, name);

    if(name.empty()) {
        cout << "You must enter a customer name.";
    }
    else
    {
        cout << "You entered " << name << endl;
    }

    return 0;
}
ark1974
  • 615
  • 5
  • 16