Verify if string contains at least one letter - c++

Hello Im trying to check if string contains at least one letter, but at this stage is not working. If I type 13 it would continue without giving me error,
It doesn't matter if contains number I just want at least one letter for example: Patrick1 thats okay.
This the code I'm trying :
void setName(string b) {
cout << "Please enter your name:" << endl;
getline(cin, b);
for (int i =0; i<b.size(); i++) {
if ((b[i] >= 'A' && b[i] <= 'Z') ||
(b[i] >= 'a' && b[i] <= 'z')) {
cout << "Error" << endl;
cout << "Please enter your name:" << endl;
getline(cin, b);
}
any suggestions thanks guys !

The C++ standard library have many nice algorithmic functions, for example one called std::any_of which will return true if any element in the range passed to causes a predicate to return true.
Can be used with ::isalpha like this
if (std::any_of(std::begin(b), std::end(b), ::isalpha))
{
// There is at least one alphabetic character in the string
}
Important note: The std::any_of function was introduced in C++11. Some compilers need special flags to enable C++11. Very old compilers and standard libraries might not have the function at all.

please try to avoid repeating yourself (like you did with "getline")
If you have to, rethink your algorithm ... in your case it could be something like " repeat the entry while there's no correct name entered", which can be coded exactly that way:
this way, if you want to change the code in place A, you cannot forget to also change it in place B (and all the other places you eventually copied it to) ;-)
#include <algorithm>
#include <iostream>
#include <cctype>
void setName(std::string& b) {
bool isValidName=false; // nothing entered yet
while ( !isValidName )
{
std::cout << "Please enter your name:" << std::endl;
std::getline(std::cin, b);
if (std::any_of(std::begin(b), std::end(b), ::isalpha)) {
isValidName=true; // correct name entered
}
else {
std::cout << "Error" << std::endl;
}
}
}
int main() {
std::string name;
setName(name);
std::cout << "Hello, " << name << "!" << std::endl;
return 0;
}

Related

Why can't I successfully run the following hangman game console code? I could successfully run the same code in devc++

error message.png
These are the errors
1."message": "cannot open source file \"iostream\"",
2.#include errors detected. Please update your includePath. Squiggles are disabled for this
translation unit (C:\Users\USER\first.cpp).
3.cannot open source file "cstdlib"
4.cannot open source file "ctime"
5.cannot open source file "string"
AND
This is my code
#include <iostream>
#include <cstdlib>
#include<ctime>
#include <string>
using namespace std;
const int MAX_TRIES=5;
int letterFill (char, string, string&);
int main ()
{
string name;
char letter;
int num_of_wrong_guesses=0;
string word;
string words[] =
{
"india",
"pakistan",
"nepal",
"malaysia",
"philippines",
"australia",
"iran",
"ethiopia",
"oman",
"indonesia"
};
//choose and copy a word from array of words randomly
srand(time(NULL));
int n=rand()% 10;
word=words[n];
// Initialize the secret word with the * character.
string unknown(word.length(),'*');
// welcome the user
cout << "\n\nWelcome to hangman...Guess a country Name";
cout << "\n\nEach letter is represented by a star.";
cout << "\n\nYou have to type only one letter in one try";
cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
// Loop until the guesses are used up
while (num_of_wrong_guesses < MAX_TRIES)
{
cout << "\n\n" << unknown;
cout << "\n\nGuess a letter: ";
cin >> letter;
// Fill secret word with letter if the guess is correct,
// otherwise increment the number of wrong guesses.
if (letterFill(letter, word, unknown)==0)
{
cout << endl << "Whoops! That letter isn't in there!" << endl;
num_of_wrong_guesses++;
}
else
{
cout << endl << "You found a letter! Isn't that exciting!" << endl;
}
// Tell user how many guesses has left.
cout << "You have " << MAX_TRIES - num_of_wrong_guesses;
cout << " guesses left." << endl;
// Check if user guessed the word.
if (word==unknown)
{
cout << word << endl;
cout << "Yeah! You got it!";
break;
}
}
if(num_of_wrong_guesses == MAX_TRIES)
{
cout << "\nSorry, you lose...you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
cin.ignore();
cin.get();
return 0;
}
/* Take a one character guess and the secret word, and fill in the
unfinished guessword. Returns number of characters matched.
Also, returns zero if the character is already guessed. */
int letterFill (char guess, string secretword, string &guessword)
{
int i;
int matches=0;
int len=secretword.length();
for (i = 0; i< len; i++)
{
// Did we already match this letter in a previous guess?
if (guess == guessword[i])
return 0;
// Is the guess in the secret word?
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
Your compiler cannot find the header files that you're including, though since you're just including headers from the standard library, there's most likely something wrong with your installation, or your environment. It could be that you're just confusing a C compiler with a C++ compiler (such as clang and clang++), or perhaps you're using a compiler that doesn't actually ship with a standard library, as is also the case with clang on Windows, which uses MSVC's standard library.
You can figure that out by trying to include a header from the C standard library, such as "stdlib.h", and see if the compiler can find it. If it can, then you're just using the wrong compiler, and if it can't, then you either lack a standard library, or your environment isn't set up properly and your compiler can't find it, but without knowing what compiler you're using, and how you're invoking it, I can't really give a detailed answer.

Retrieve all data via void function

Been trying to find a way through this. I am new to C++ and creating a simple program to get the user data, validate and cout to the screen. What i'm trying to do is to have the one function use pointers to get the users input and display back to them. This may have been answered before but I haven't had much luck finding it.
So far i have the below code
#include <iostream>
using namespace std;
void userData(int&);
int main(){
int a = 0;
int * kmpointer;
int * dayspointer;
userData();
cout << "You ran " << userData(kmpointer) << endl;
cout << "in " << userData(dayspointer) << "days!!" <<endl;
}
void userData(int& i){
cout << "Enter how Many Km's you ran:";
while (true)
{
cin >> kmpointer;
if ((cin) && (kmpointer >= 0) && (inputYear <= 100))
break;
cin.clear();
cin.ignore( 100, '\n' );
cout << "That can't be right!\n";
cout << "Enter how Many Km's you ran:";
}
cout << "How many days in a row did you run?";
while (true)
{
cin >> dayspointer;
if ((cin) && (dayspointer >= 1) && (dayspointer <= 100))
break;
cin.clear();
cin.ignore( 1000, '\n' );
cout << "Thats way to much!";
cout << "How many days in a row did you run? ";
}
}
IMO, you should start with some reading about C++. You are missing some basic concepts and trying too complex exercises for your level.
1
function is not declared/defined.
2
userData is declared accepting a parameter, but used without.
3
The problem you face is related probably with what we call scope: A variable is only existing and visible within its scope (usually enclosed by { and }.
In your case, kmpointer and dayspointerare only visible within the main function and thus, you cannot use them in userData.
To solve that, I suggest you to pass those variables as parameters for userData.
4
Pointers, references, values: They are different. You are saving the user input as a pointer address, which is indeed problematic.
General
In general, your code is full of mistakes. Try a Hello world! and continue from there steps by steps.
Focussing on the specific question you asked (though as observed you have other problems in your code), don't use pointers, use references.
Before we get to that this
cout << "You ran " << userData(kmpointer) << endl;
won't compile, since as you know userData is a void function, so applying << to it makes no sense. It's void so there's nothing to stream.
You said you wanted to pass parameters into the function and let them be changed so do that. Then display the variables afterwards. (Not the "result" of a void function call).
Correctly getting the user input is a separate question which has been answered before.
#include <iostream>
using namespace std;
void userData(int& i, int& j, int& k);
int main() {
int a = 0;
int kmpointer;
int dayspointer;
//Here we call our function, ONCE
userData(a, kmpointer, dayspointer);
//Here we display what values we now have
//after calling the function, ONCE
cout << "You ran " << kmpointer << endl;
cout << "in " << dayspointer << " days!!" << endl;
}
//simplified to demonstrate changes to the reference parameters
void userData(int& i, int& j, int& k) {
//Here we have three parameters which we refer to as i, j and k
// They may have different names ousdie in the calling code
// but this function (scope) neither knows nor cares
j = 42;
k = 101;
}

how to rewrite this c++ simple code?

the code bellow is a c++ code that works just perfectly, the teacher asked us to rewrite it in order to have the input and output in only one instruction.
i really don´t know how to, and i have done research for hours.
i'll really appreciate a hint on how to do this.
#include <iostream>
using namespace std;
int main()
{
int c;
cin >> c;
std;
if(c == 0) {
cout << "user sent 0" << endl;
}
else {
cout << "user sent a number different from 0" << endl;
}
return 0;
}
thanks for reading.
If your teacher considers an if-else statement as one instruction, I can propose this one:
#include <iostream >
using namespace std;
int main() {
int c;
if ( (cin >> c) && c==0 )
cout << ”user sent 0” << endl ;
else cout << ”user sent a number different from 0” << endl ;
return 0;
}
If he sees it more strictly, then you can try :
int c;
cout << ( (cin >> c) && c==0 ? "user sent 0" : "user sent a number different from 0" ) << endl;
return 0;
Conceptually, I love the last one. But when I read it again, it reminds me B.Kernighan's famous quote : "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."
This is the smallest I can do:
std::cout << (std::cin.get() == '0' ? "user sent 0" : "user sent a number different from 0");

An exercise asks me to change the body of the loop. What does it mean?

I am fairly new to C++ still, as well as programming and the terms used. I'm learning off of "Programming: Principles and Practice Using C++" (as was gifted to me) and I ran into a problem on a Drill at the end of chapter four. The drill is split into twelve exercises, where the first five are as follows:
Write a program that consists of a while-loop that (each time around the loop) reads in two ints and then prints them. Exit the
program when a terminating '|' is entered.
Change the program to write out the smaller value is: followed by the smaller of the numbers and the larger value is: followed by the
larger value.
Augment the program so that it writes the line the numbers are equal (only) if they are equal.
Change the program so that it uses doubles instead of ints.
Change the program so that it writes out the numbers are almost equal after writing out which is the larger and the smaller if the two
numbers differ by less than 1.0/100.
I've dealt with those exercises, but now I don't quite get what to do in the next exercise:
Now change the body of the loop so that it reads just one double each time around. Define two variables to keep track of which is the smallest and which is the largest value you have
seen so far. Each time through the loop write out the value entered. If it’s the smallest so far, write the smallest so far after the number. If it is the largest so far, write the largest so far after the number.
I don't get it. What should I do with the loop? What's exercise 6 actually about?
My code I have made up so far from step five is as follows:
#include <iostream>
#include <vector>
#include <algorithm>
//Name
int main()
{
char terminate = ' ';
double one = 0.0;
double two = 0.0;
int one_i = one;
int two_i = two;
while (terminate != '|')
{
std::cout << "Input two numbers, follow each one by enter: " << std::endl;
std::cin >> one;
std::cin >> two;
if (one == two)
{
std::cout << "The two numbers are equal to each other." << std::endl;
std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
std::cin >> terminate;
if (terminate == '|')
{
break;
}
}
std::cout << "Here is the larger value: ";
if (one > two)
{
std::cout << one << std::endl;
}
else
{
if (two > one)
{
std::cout << two << std::endl;
}
}
std::cout << "Here is the smaller value: ";
if (one < two)
{
std::cout << one << std::endl;
if (one_i == two_i || two_i == one_i)
{
std::wcout << "The numbers are almost equal." << std::endl;
}
}
else
{
if (two < one)
{
std::cout << two << std::endl;
if (one_i == two_i || two_i == one_i)
{
std::wcout << "The numbers are almost equal." << std::endl;
}
}
}
std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
std::cin >> terminate;
}
}
I attempted to figure out the problem if this code helps any of you see as to what degree I'm confused on.
#include <iostream>
#include <vector>
#include <algorithm>
//Name
int main()
{
char terminate = ' ';
std::vector<double>num_size;
while (terminate != '|')
{
std::cout << "Type in a number: " << std::endl;
for (double num; std::cin >> num;)
{
num_size.push_back(num);
std::sort(num_size.begin(), num_size.end());
}
std::cout << "To terminate this program, type \"|\" into the system followed by pressing enter twice." << std::endl;
std::cin >> terminate;
}
}
Well, you didn't finish step 5. 999 and 1000 are almost equal (difference < 1%).
Ignoring that, your second fragment is a good start at producing the behavior wanted in step 6 but ignores the prescribed method. Yes, a sorted vector has a .front() and a .back() which are the respective minimum and maximum, but step 6 specifically told you to use two variables instead of a whole vector.
So double max = std::numeric_limits<double>::max(); double min = -max; and from there on you should be able to figure it out.
You want something like:
double my_max = numeric_limits<double>::max();
double my_min = -1 * numeric_limits<double>::max();
while (...) {
...
my_min = min(my_min, one);
my_min = min(my_min, two);
my_max = max(my_max, one);
my_max = max(my_max, two);

How do i take the initials of all the parts of one's name except the last name?

Hi i am trying to write a c++ program where the user will enter a name lets say for example: Tahmid Alam Khan Rifat and the computer will print the formatted version of the name which in this case will be: Mr. T. A. K. Rifat. I have included the code below. You will be able to see that I got close but still not exactly what i wanted. Please help.
#include<iostream>
#include<string>
using namespace std;
class myclass{
private:
string name,temp;
string p;
int i,j,sp;
public:
void work(){
cout << "Enter the name of the male student: ";
getline(cin,name);
cout << endl;
cout << "The original name is: ";
cout << name;
cout << endl << endl;
cout << "The formatted name is: " << "Mr." << name[0] << ".";
for(i=0;i<name.size();i++){
if(name[i]==' '){
sp=i;
for(j=sp+1;j<=sp+1;j++){
temp=name[j];
cout << temp << ".";
}
}
}
for(i=sp+2;i<name.size();i++){
cout << name[i];
}
cout << endl;
}
};
int main(){
myclass c;
c.work();
}
I guess the easiest way to solve this is to tokenize your string, print the first character from it, except from the last, where you print its full size.
To tokenize, you can do something like that:
std::vector<std::string> tokenize(std::istringstream &str)
{
std::vector<std::string> tokens;
while ( !str.eof() ) {
std::string tmp;
str >> tmp;
tokens.push_back(tmp);
}
return tokens;
}
Now you can easily transverse the tokens:
int main()
{
std::string name;
cout << "Enter the name of the male student: ";
getline(cin,name);
cout << endl;
cout << "The original name is: ";
cout << name;
cout << endl << endl;
std::istringstream str(name);
std::vector<std::string> tokens = tokenize(str);
for ( int i = 0 ; i < tokens.size() - 1; ++i)
std::cout << tokens[i][0] << ". ";
cout << tokens[tokens.size() - 1] << endl;
}
I hope this helps :)
It is probably a simpler version (originally I wrote this in C, you could easily convert it to C++ though, since the logic remains the same).
I have accepted the name and then inserted a space at the beginning of the string and one more space at the end, before the NULL character ('\0')
The program checks for a space.
When it encounters one, it checks for the next space that occurs in the string.
Now occurrence of this space helps us to identify an important determining factor as to what the next action should be.
See, if there is an null character after this subsequent space, then we can conclude that the subsequent space was the one we inserted at the end of the string.
That is, the space which occurs after the primary space, which came before the surname. Bingo!
You get the precise index of the array, from where the surname starts! :D
Looks long, but really is simple. Good luck!
#include<stdio.h>
#include<string.h>
void main()
{
char str[100]; /*you could also allocate dynamically as per your convenience*/
int i,j,k;
printf("Enter the full name: ");
gets(str);
int l=strlen(str);
for(i=l;i>=0;i--)
{
str[i+1]=str[i]; //shifting elements to make room for the space
}
str[0]=' '; //inserting space in the beginning
str[l+1]=' '; str[l+2]='\0'; //inserting space at the end
printf("The abbreviated form is:\n");
for(i=0;i<l+1;i++) //main loop for checking
{
if(str[i]==' ') //first space checker
{
for(j=i+1; str[j]!=' ';j++) //running loop till subsequent space
{
}
if(str[j+1]!='\0') //not the space after surname
{
printf("%c.",str[i+1]); //prints just the initial
}
else
for(k=i+1;str[k]!='\0';k++) //space after surname
{
printf("%c", str[k]); //prints the entire surname
}
}
}
}
Change your loop to the following:-
for(i=0;i<name.size();i++)
{
if(name[i]==' ')
{
initial = i + 1; //initial is of type int.
temp = name[initial]; //temp is char.
cout << temp << ".";
}
}
Try ravi's answer to make your code work, but I wanted to point out that there are more intuitive ways to program this which would make maintenance and collaboration easier in the future (always a good practice).
You can use an explode() implementation (or C's strtok()) to split the name string into pieces. Then just use the first character of each piece, disregarding the last name.
I think your question has already been answered. But in the future you could consider splitting up your program into more simple tasks, which makes things easier to read. Coupled with descriptive variable and function names, it can make a program easier to comprehend, and therefore to modify or fix later on.
Disclaimer - I am a beginner amateur programmer and this is just for ideas:
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
// I got this function from StackOverflow somewhere, splits a string into
// vector of desired type:
template<typename T>
std::vector<T> LineSplit(const std::string& line) {
std::istringstream is(line);
return std::vector<T>(std::istream_iterator<T>(is), std::istream_iterator<T>());
}
class Names {
private:
std::vector<std::string> full_name_;
void TakeInput() {
std::cout << "Enter the name of the male student: " << std::endl;
std::string input;
getline(std::cin,input);
full_name_ = LineSplit<std::string>(input);
}
void DisplayInitialsOfFirstNames() const {
std::cout << "Mr. ";
for (std::size_t i = 0; i < full_name_.size()-1; ++i) {
std::cout << full_name_[i][0] << ". ";
}
};
void DisplayLastName() const {
std::cout << full_name_.back() << std::endl;
}
public:
void work() {
TakeInput();
DisplayInitialsOfFirstNames();
DisplayLastName();
};
};
int main(){
Names n;
n.work();
}