i wanted to take input of letters only but its not working properly. if i input a random string like abcd123 it repeats try again when i enter again same abcd123 it will output ignoring the condition i want this only to take abcd.
#include <iostream>
#include <string>
using namespace std;
bool IsLetters(string &input)
{
for (int i = 0; i < input.size(); i )
{
int uppercaseChar = toupper(input[i]); //condition for letters
if (uppercaseChar < 'A' || uppercaseChar > 'Z')
{ cout<<"try again\n";
cin>>input;
return IsLetters;
}
}
return true;
}
int main()
{
string x;
cout<<"enter your name\n";
cin>>x; //string input
if (IsLetters(x)) // function call
{
cout << "your name is\n"<<x;
}
return 0;
}
CodePudding user response:
you need to change logic, pls try following
#include <iostream>
#include <string>
using namespace std;
bool IsLetters(string& input)
{
for (int i = 0; i < input.size(); i )
{
int uppercaseChar = toupper(input[i]); //condition for letters
if (uppercaseChar < 'A' || uppercaseChar > 'Z')
{
return true;
}
}
return false;
}
int main()
{
string x;
cout << "enter your name\n";
cin >> x; //string input
while (IsLetters(x)) // function call
{
cout << "try again\n";
cin >> x;
}
cout << "your name is\n" << x;
return 0;
}
CodePudding user response:
You can try this straightforward solution.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cout <<"enter your name\n";
cin >> s;
int flag = false;
while (flag != true)
{
for (int i = 0; i < s.size(); i )
{
if (!(s[i] >= 'A' && s[i] <= 'Z') && !(s[i] >= 'a' && s[i] <= 'z'))
{
flag = true;
break;
}
}
if (flag == true)
{
cout<<"try again\n";
flag = false;
cin >> s;
} else {
cout << s;
break;
}
}
return 0;
}