0
#include<iostream>
using namespace std;

void main()
{

    char fname[11]; 
    int x = 0; 

    cout << "Please enter the name: "; 
    cin >> fname;

    while (fname[x] != '\0') 
    { 
        int i=int(fname[x]);
        if (i>=97)
            cout << fname[x]; 
        x++; 
    } 

    else    
        cout << "Invalid characters";

    system("pause");
}

I tried to validate char input by using above codes. But couldn't do it.

What is wrong with these codes?

wkl
  • 77,184
  • 16
  • 165
  • 176
Nera
  • 117
  • 1
  • 1
  • 8
  • 5
    What are you trying to do? Your `else` block has no corresponding `if` block. [The return type of `main` is `int`, not `void`](http://stackoverflow.com/questions/4207134/what-is-the-proper-declaration-of-main/4207223#4207223). You should use a `std::string` instead of a `char[11]`; `cin >> fname` is a gaping security bug (consider what happens if the user inputs more than ten characters). – James McNellis Nov 29 '10 at 18:18

2 Answers2

6
  • in C++ it's int main instead of void main,
  • you should use std::string instead of char arrays (safer, more convenient),
  • for testing if a single character is a letter, there are functions defined in <cctype>, like isalpha(),
  • you cannot have an "else" without an "if".

Try to draw a flow diagram for what you want to achieve.

Kos
  • 70,399
  • 25
  • 169
  • 233
0

You should be getting a compilation error about the else. The proper syntax for else is:

if (expression)
{  // this is done is expression is true
}
else 
{ // this is done if expression is false
}

You might also want a break statement in your else once you move it into the while.

Lou Franco
  • 87,846
  • 14
  • 132
  • 192