Character Validation in C++, simple but help needed.

Rahul++

SuperUser
Skilled
Hello,

I've written a simple C++ code for taking values from user. But I need little help with validation. I want to check null validation only.

Here is the partial code -

Code:
    char name[20];

    char surname[20];

    char city[20];

  cout<<"\n\t\tFirst Name : ";

  gets(name);

  cout<<"\n\t\tSurname : ";

  gets(surname);

  cout<<"\n\t\tCity : ";

  gets(city);

This is only that part of code. Now what I need is to check if the user haven't entered anything (i.e. name == null something)

The problem I'm getting is, whenever I run the program, and Hit Enter key without entering anything, the program crashes.. I need help with null validation.
 
This should do

Code:
#include<iostream>

#include<cstdio>

using namespace std;

int main()

{	

	char name[4];
        t:

	cout<<"Enter your name \n";

	gets(name);

	if (name[0]=='\0')

	{

		goto t;

	}

	cout<<"your name\t"<<name;

}

However use of gets is not good for program and might overflow the buffer into which input is place. So rather use other options.
 
You can also use the condition

Code:
if (*name == null) {

}
Since an array is a contiguous chunk of memory, *name will refer to the first element in the array. Alternatively you can also use string lib functions to accomplish the same thing.
 
please, start using std::string. Using a character array will lead to lot's of problems not worth it. You could use cin.getline() to read a line. You don't need to worry about buffer overflow and all.

@Lord Nemesis You perhaps meant NULL? null character(\0) and NULL aren't the same thing, implicitly converted to int, they are.
 
Back
Top