Home > OS >  Using a value that can be approved if the user input was null
Using a value that can be approved if the user input was null

Time:04-28

I am still a beginner in C but I have tried several methods to let the user only have one chance to get a value from the user if the user pressed enter without putting any value then it prints another value that I chose.

I tried:

#include <iostream>
#include <string>
using namespace std;
int main() {
  char var;
  cin.get(var);
  if (&var == NULL)
    cout << "d";
  else
    cout << var;
}

Also I tried

#include <iostream>
#include <string>

using namespace std;
int main() {
  string value;

  while (value == null) {
    cin >> value;
    if (value != NULL)
      cout << value << " ";
    else
      cout << "hello"
  }
}

CodePudding user response:

if (&var == NULL)

This test will never be true. Address of an automatic variable is never null.

A simple way to check whether a stream extraction was successful is to check the state of the stream by (implicitly) converting it to bool:

char var;
std::cin >> var;
if (std::cin)
    std::cout << var;
else
    std::cout << "extraction failed";

but if i just clicked an enter it will not display the "extraction failed"??

The stream extraction operator won't accept pressing enter on an empty prompt. It will wait until you input at least one character before enter. You can intentionally provide empty input by sending the EOF control character (End Of File). How to do that depends on what shell you are using. On Linux, it's typically ctrl d while on Windows it's typically ctrl z.

If you want the behaviour of accepting enter on empty input, then you can use the get member function as you did in the question, and check whether the input character was the newline character:

cin.get(var);
if (var != '\n')
    std::cout << var;
else
    std::cout << "extraction failed";
  •  Tags:  
  • c
  • Related