0

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"
  }
}
David G
  • 94,763
  • 41
  • 167
  • 253
kimo_liz
  • 35
  • 8
  • 1
    What is the topic of the chapter from the C++ textbook that this practice problem is from? The topic would be a hint as to which parts of the C++ language are expected to be used in implementing this task. – Sam Varshavchik Apr 27 '22 at 22:50
  • value can not be NULL. c++ does not have that concept. a char is always a char never null. A string can be an empty string – drescherjm Apr 27 '22 at 22:50
  • Have you tried setting `var` to `" "` to represent empty string or `' '` for empty char instead of NULL? – chickennuggies Apr 27 '22 at 22:51
  • `if (&var == NULL)` var is a local variable its address is not equal to NULL even if you did not input anything to it. if you do `char var; if (&var == NULL) { }` your if condition would never be true. – drescherjm Apr 27 '22 at 22:53
  • Related: [https://stackoverflow.com/questions/29546193/the-concept-of-nil-in-c](https://stackoverflow.com/questions/29546193/the-concept-of-nil-in-c) – drescherjm Apr 27 '22 at 22:57

1 Answers1

1
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";
eerorika
  • 232,697
  • 12
  • 197
  • 326