I have a string array with multiple names.
I would like to check using an if statement if the user input is equal to any of the names.
For example:
names[5] = {'david','rares','tudor','john','jay'}
cin>>name;
And now i would like to check if name is equal to any of the elements in the array.
Very Bad Example:
if(name == names)
{
cout<<"you can use this name. Name: "<<name;
}
As pointed out by user4581301, 'david' isn't a string but a multibyte character (and most probably not a valid one either). If you want to keep a set of names and check if some name exists in it, you could use a std::set or std::unordered_set instead of an array. Example:
#include <iostream>
#include <set>
#include <string>
int main() {
std::set<std::string> names = {"david", "rares", "tudor", "john", "jay"};
std::string name;
std::cin >> name;
if(names.count(name)) // or names.contains(name) in C++20
std::cout << "found\n";
else
std::cout << "not found\n";
}
I would suggest using a vector to store the names so you know your size. If you must use a static array, make sure to save the current size and update it whenever removing/adding names.
Somebody may have a more efficient solution, but you can linearly search through the array using a for loop.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
string names[5] = {"david","rares","tudor","john","jay"};
cout << "Enter name: ";
cin >> name;
for (int i = 0; i < 5; i++)
{
if(names[i] == name)
{
cout << name << " was found in the array." << endl;
return 0;
}
}
cout << name << " wasn't found in the array." << endl;
return 0;
}
This solution won't work for case sensitive names (David and david are considered two seperate names).
You can do something like this:
#include <iostream>
#include <algorithm>
int main()
{
const char * v [] = { "david", "rares", "tudor", "john", "jay" };
std::string name;
std::cin >> name;
auto result = std::find (std::begin (v), std::end (v), name);
if (result != std::end (v))
std::cout << name << " is valid\n";
}
although please note that most people would use std::vector <std::string> to hold the list of strings.
Live demo
Related
I just started learning C++ and I'm currently following a tutorial on YouTube.
I thought it was fun to make a very simple 'access' program. If I type in my name it says, "Welcome!" If I type in another name it says, "access denied". It worked perfectly fine, but then I wanted the program to say "Welcome!" to two different names. So, I wanted to add a second name in the string, but I couldn't figure out how to do that. I googled a lot but I couldn't find anything. In the end, I came to string name = ("Joe", "Sean");, but here, it was only valid for Sean. I just can't figure out how to put multiple names in one string and make them both work. I hope you can help me, here is my code:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string name = ("Joe", "Sean");
string input;
cout << "What is your name?\nMy name is: ";
cin >> input;
if(input == name){
cout << "Welcome, "<< input <<"! ";
} else {
cout << "Access denied";
}
return 0;
}
This is a way to do it using a vector of strings, so you can adapt easily with more names :
#include <iostream>
#include <vector>
using namespace std;
void printMessage(string message)
{
std::cout << message << std::endl;
}
int main()
{
vector<string> names{"Joe", "Sean", "Paul"};
string input;
cout << "What is your name? " << endl;
cin >> input;
for (string name : names)
{
if (name == input)
{
printMessage("Welcome!");
return 0;
}
}
printMessage("Access Denied!");
return 0;
}
The problem is in the string variable "name". You need an array of strings, not a single string.
This is an example implementation:
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string names[] = {"Joe", "Sean"};
string input;
cout << "What is your name?\nMy name is: ";
cin >> input;
for (int i = 0; i < end(names) - begin(names); i++) {
if(input == names[i]){
cout << "Welcome, "<< input <<"! " << endl;
return 0;
}
}
cout << "Access denied" << endl;
return 0;
}
You encountered some quirky features of C++ in the approach you are using to initialize your string variable:
string s1 = ("Joe"); // creates a string "Joe"
string s2 = ("Joe", "Sean"); // creates 2 strings, "Joe" and "Sean", and the variable s2 stores only the latter!
For more details on the different methods for initializing variables there has been an interesting discussion in this previous question.
I am working on a code for my c++ class. The assignment is to read the names from 2 different txt files(already in my directory) and find if the string/name that the user searched for matches any of the names already in the files. My code seems good to me, but I am getting an error in my function prototype saying "string was not declared in this scope." Any solutions? My code is here as follows:
#include <fstream>
#include <string>
#include <vector>
void boysfunc(string&, string&);
void girlsfunc(string&, string&);
using namespace std;
int main()
{
vector<string> boysnames;
vector<string> girlsnames;
string boysname, girlsname;
ofstream outputFile;
cout << "Enter a boy's name, or N if you do not want to
enter a name: ";
cin >> boysname;
cout << "Enter a girl's name, or N if you do not want to
enter a name: ";
cin >> girlsname;
if (boysname != "N")
{
boysfunc(boysname, boysnames);
}
if (girlsname != "N")
{
girlsfunc(girlsname, girlsnames);
}
}
void boysfunc(string &boysname, string &boysnames)
{
outputFile.open("BoysNames.txt");
while(outputFile >> boysnames)
{
/*Declare local variable count to use as a counter*/
int count = 0;
if (boysnames(count) == boysname)
{
outputFile.close();
cout << "The name " << boysname << " is very
popular among boys.";
return;
}
else
{
count++;
}
}
}
void girlsfunc(string &girlsname, string &girlsnames)
{
outputFile.open("GirlsNames.txt");
while(outputFile >> girlsnames)
{
/*Declare local variable count to use as a counter*/
int count = 0;
if(girlsnames(count) == girlsname)
{
outputFile.close();
cout << "The name " << boysname << " is very
popular among girls.";
return;
}
else
{
count++;
}
}
}
There are two major errors that you need to fix here.
using namespace std; must be written before the use of strings if you wish to omit std:: before writing string. Otherwise, you can write std::string& in the function declarations.
boysfunc() and girlsfunc() are taking vector<string>& as the second argument, whereas you incorrectly mentioned string& in the functions' declaration and definition. Fix that.
In this snippet
string s = "hello";
using namespace std;
the type string is not known to the compiler. That's what using namespace std; does. It basically turns string into std::string.
You could swap the 2 lines above, and it will work, but I highly recommend just saying std::string explicitly everywhere. I'm sure your IDE will let you do this easily.
The final element in the vector is the char to search for.
Here’s my code:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
vector<string> words;
string in;
while(cin>>in)
{
words.push_back(in);
}
int size = words.size()
string check = words.at(size-1);
}
I tried your code and the loop was infinite. Try asking a set number of words then use the find method for each string. Here's an example.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<string> words;
string in;
cout << "Enter 5 words: \n";
for (int i{0}; i < 5; ++i)
{
cout << "Word: ";
cin >> in;
words.push_back(in);
}
cout << "What character do you want to search for? ";
char c;
cin >> c;
for (auto word : words)
{
if (word.find(c) != string::npos)
{
cout << "Character \"" << c << "\" found in " << word << endl;
}
}
return 0;
}
Edit: I noticed that you tried to use int to store the size for the string. Use size_t instead. I also think you meant to use the length method of the string, which also returns size_t.
I need help ... How do I get the this program to read what the person type as a string and see if the strings are equal?
#include <iostream>
using namespace std;
int main()
{
char name;
cout << "Type my name is:";
cin >> name;
if
name ==char('Mike') //this is where i think the problem is...
cout << "congrats";
else
cout << "Try again";
}
#include <iostream>
int main()
{
std::string name;
std::cout << "Type my name is:";
std::cin >> name;
if (name == "Mike") // Compare directly to the string "Mike"...
std::cout << "congrats";
else
std::cout << "Try again";
}
I think it is always better habit to use std:: instead of using namespace std.
Have you tried using std::string in c++?
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Type my name is:";
cin >> name;
if (name == "Mike"))
cout << "congrats";
else
cout << "Try again";
}
Your problem is that char is a character variable, not a character array. If you want to create a 'c-string' (collection of characters), use char name[20]. To create a string object, use string name. Don't forget to #include <string>. Here's a brief tutorial for strings:
http://www.cplusplus.com/doc/tutorial/ntcs/
If you want to use c-strings, you have to use strcmp(name,"Mike") to compare two strings. It returns true if two strings are DIFFERENT, so be careful.
#include <iostream>
using namespace std;
int main()
{
char name[20];
cout << "Type my name is:";
cin >> name;
if (!strcmp(name,"Mike")) //C string equality tester
cout << "congrats";
else
cout << "Try again";
}
Strings are easier to use because you can just use the equality operator ==.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
cout << "Type my name is:";
cin >> name;
if (name == "Mike") //Tests for equality using strings
cout << "congrats";
else
cout << "Try again";
}
Also, watch your quotation marks. Single quotes ('a') are for characters, double quotes ("Mike") are for character arrays (words, sentences, etc.)
char is a single character, replace all your char with std::string and add #include <string> to the beginning of you code. std::string will save arbitrary length strings.
if is followed by braces: if(...). In your case if(name == char('Mike')) or with the advice from above if(name == std::string('Mike')).
In C and C++ the two quotes ' and " are different. You use ' for single characters and " for strings. So it needs to be if(name == std::string("Mike")).
You may also write if(name == "Mike").
Also you should make brackets to increase readability and avoid errors. After if(...) you would usually use {} to encapsulate the instructions to be executed if the condition in if(...) is met. Your case is special, because the brackets may be left out for single instructions.
if(...)
{
...
}
else
{
...
}
int main()
{
string name;
string myname("Mike");
cout << "Type my name is:";
cin >> name;
if(name ==myname) //this is where i think the problem is...
{
cout << "congrats";
}
else
cout << "Try again";
}
This should do it. But I'm sure you don't want to hard-code "Mike" ONLY. A good improvement would be to get names from a file and then compare. Also keep in mind that string == operator is case sensitive so "Mike" != "mike"
The stated problem is "Write a program that takes names and ages of 10 employees as input in a 2D char array and display their names in ascending order with respect to their ages".
I've pasted below what I have so far, but I don't know how to display the names in ascending order with respect to age. What am I missing?
#include<iostream.h>
#include<string.h>
void sort(int[],int);
void main(void)
{
char a[10][5],x;
int b[5],i,j;
for(j=0;j<=5;j++)
{
cout<<"Enter name of Employee:";
for(i=0;i<10;i++)
{
cin>>x;
x=a[j][i];
}
cout<<"Enter Employee's age:";
cin>>b[j];
cout<<endl;
}
sort(b,j);
cout<<"Name of Employee \t\t Age \n";
for(j=0;j<5;j++)
{
for(i=0;i<10;i++)
{
x=a[j][i];
cout<<"\t"<<x;
}
cout<<"\t\t"<<b[j]<<"\n";
}
}
void sort(int x[],int size)
{
int temp,i,j;
for(j=0;j<size;j++)
{
for(i=0;i<size;i++)
{
if(x[i]>x[i+1])
{
temp=x[i+1];
x[i+1]=x[i];
x[i]=temp;
}
}
}
}
I will point you in the right direction.
You should define struct to hold a Name and age pair, then make a comparison function.
Then you simply need to populate a vector of your structs then sort them using the sorting function provided by the standard library, iterate through the vector printing out the contents, you can define stream operator of the struct you made to simplify them.
http://www.cplusplus.com/doc/tutorial/structures/
http://en.cppreference.com/w/cpp/algorithm/sort
http://en.cppreference.com/w/cpp/container/vector
http://www.java2s.com/Code/Cpp/Overload/Overloadstreamoperator.htm
EDIT: and please for all that is good, use a std::string to hold the names.
http://www.cplusplus.com/reference/string/string/
using an char array like you are is pretty much deprecated.
I started writing this before the other solution, because I would rather see what C++ is capable of not what your lecture is feeding you.
#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
struct employee
{
employee(const std::string& name_, unsigned age_)
: name(name_), age(age_) {}
std::string name;
unsigned age;
};
std::ostream& operator<<(std::ostream& os, const employee& e)
{
os << e.name << " " << e.age;
return os;
}
bool comp_age(const employee& e1, const employee& e2)
{
return e1.age<e2.age;
}
int main()
{
std::vector<employee> employees;
employees.reserve(5);
for(unsigned i=0; i!=5; ++i)
{
std::string name;
unsigned age;
std::cout << "Name:" << std::flush;
std::cin >> name;
std::cout << "Age:" << std::flush;
if(!std::cin >> age)
{
std::cerr << "not an number" << std::endl;
--i;
continue;
}
//note you should catch any failure to parse to int here
employees.push_back(employee(name, age));
}
std::sort(employees.begin(), employees.end(), comp_age);
std::copy( employees.begin(), employees.end(),
std::ostream_iterator<employee>(std::cout, "\n"));
return 0;
}
So this is an alternative, but PLEASE learn the concepts I list above which constitutes this example.
You should start by changing void main to int main, because void main is not valid C++. Then you change the #includes to be real C++ header files not what you have:
#include <iostream>
#include <string>
Then you should give meaningful names to your variables. It's impossible to follow the code in a sea of as and bs.
Then you need to sort the employees by their age. You already have a sorting algorithm written there, so you only need to adapt it to swap all the employee data instead of swapping just their ages, while still doing the comparisons only on their age. This will be easier if instead of two separate arrays for the employee data, you kept instead a single array of a structure that holds both the name and age of the employee:
struct employee {
std::string name;
int age;
};
Once sorted, you can just loop through all the employees an print their names.
I believe there are a few more issues in the code, but they should be easy to fix with a good reference and some debugging time. If you have trouble, you can post a new question with what you've got so far, and explain what is stumping you.
This would all be much better if you just used the C++ standard library, but unfortunately some teachers decide to teach Crippled++ to their students instead of proper C++ :(
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
// treat an employee as a single unit
struct employee {
std::string name;
int age;
};
// a comparison function to compare two employees by their age
// should return true if the first one is younger than the second one
// this will be used for sorting later
bool is_younger(employee const& l, employee const& r) {
return l.age < r.age;
}
int main()
{
// a vector with 5 employees
std::vector<employee> employees(5);
for(j=0;j<=5;++j)
{
std::cout << "Enter name of Employee: "
// read the entire name at once
getline(std::cin, employees[j].name);
std::cout << "Enter Employee's age:";
// read the age
std::cin >> employees[j].age;
}
// sort all the employees using the comparison function written above
std::sort(employees.begin(), employees.end(), is_younger);
std::cout<<"Name of Employee \t\t Age \n";
for(j=0;j<5;++j)
{
std::cout << employees[j].name;
std::cout << "\t\t" << employees[j].age << "\n";
}
}
Use a std::multimap (a key/value store, fitting your needs), which is weakly sorted ascending by default. Your key is the age and the value is the name. For printing the values just use iterators. std::multimap is chosen because there could potentially be employees with the same age.
#include <iostream.h>
int main() {
int a;
int b;
int sum;
std::cout << "Enter two numbers" << std::endl;
std::cout << "Enter the value of a" << std::endl;
std::cin >> a;
std:: cout << "Enter the value of b" << std::endl;
std::cin >> b;
sum = a + b;
std::cout << sum << std::endl;
return 0;
}