L
L
Lisik2018-11-18 15:54:52
C++ / C#
Lisik, 2018-11-18 15:54:52

How to compare with Enter?

Hello, I'm new to C++ and I have a question. I need that when entering a name, it cannot be just an empty space (by pressing the Enter key). To do this, I put a comparison condition, but it does not work. Help me fix it please.
stringname1;

string name1;
  cout << "'Придумай себе умопомрачительное имя': ";
  while (cin.get() != '\n');
  getline(cin, name1);
  if (name1 == '\n') {
    cout << "Ты, вроде как, имя не ввел. Так это, то самое, давай, обзови себя как-нибудь..." << endl;
    goto label3;
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Artem Spiridonov, 2018-11-18
@customtema

No need to compare with Enter.
It is necessary to trim whitespace characters (space, tabs, newline characters and "carriage return") from the edges of the received one, and estimate the size of the received line. Further - to work with the trimmed line.

R
Roman, 2018-11-18
@myjcom

Can it be like this
#include<iostream>
#include<string>

using namespace std;

int main()
{
  setlocale(LC_ALL, "Russian");
  system("chcp 1251 > null");
  string s;
  cout << "Введите имя: ";
  while(getline(cin, s))
  {
    if(s.empty())
    {
      cout << "Вы не ввели имя!\n"
           << "Введите имя: ";
      continue;
    }
    break;
  }
  cout << "\nВаше имя: " << s
       << "\nНажмите любую клавишу...";
  cin.get();
}

If more correctly, as Artem Spiridonov writes ,
Then perhaps so (Windows)
#include<iostream>
#include<string>
#include<algorithm>
#include<cctype>
#include<clocale>

using namespace std;

/* functions from https://code-examples.net/ru/q/34ef7 */
// trim from start (in place)
static inline void ltrim(string &s)
{
  s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](const auto ch) {
    return !isspace(ch);
  }));
}

// trim from end (in place)
static inline void rtrim(string &s)
{
  s.erase(std::find_if(s.rbegin(), s.rend(), [](const auto ch) {
    return !isspace(ch);
  }).base(), s.end());
}

// trim from both ends (in place)
static inline void trim(string &s)
{
  ltrim(s);
  rtrim(s);
}

int main()
{
  setlocale(LC_ALL, "Russian");
  system("chcp 1251 > null");
  string s;
  cout << "Введите имя: ";
  while(getline(cin, s))
  {
    //upd
    replace_if(s.begin(), s.end(), [](const auto c){return iscntrl(c); }, ' ');
    trim(s);
    //end upd

    if(s.empty())
    {
      cout << "Вы не ввели имя!\n"
           << "Введите имя: ";
      continue;
    }
    break;
  }
  cout << "\nВаше имя: " << s
       << "\nНажмите любую клавишу...";
  cin.get();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question