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.
Related
I have a problem. I want to create an integer by user input. For example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i = 0;
char newVar;
string newVarName;
cout << "New Variable? (y/n)" << endl;
cin >> newVar;
if (newVar == 'y') {
/* newVarName declares new int with the name
of the user input (newVarName = test --> int test)*/
} else {
break;
}
return 0;
}
How can I do this?
As #Fantastic Mr Fox mentioned :
int name_dependant_on_user_input = value_from_user
This is impossible in c++, because the variable name, is a compile
time thing. The user input happens at runtime, which is after
compilation has completed. Something you could do, is map a string
input to your user input, for eg.
Some other error: String should be string or std::string. And using break; while not within loop or switch statements will return an error. If you want to escape immidiately, you could use exit(0);
Otherwise, as #Eljay mentioned above, a map<string, int> can be used to store both the name and value of your variable:
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
char newVar;
string newVarName;
map<string, int> varName;
cout << "New Variable? (y/n) : ";
cin >> newVar;
if (newVar == 'y') {
cout << "Name : "; cin >> newVarName;
cout << "Int : "; cin >> varName[newVarName];
} else {
exit(0);
}
//testing
cout << "Test : " << newVarName << " = " << varName[newVarName];
return 0;
}
Result:
New Variable? (y/n) : y
Name : var
Int : 5
Test : var = 5
Also, see why using namespace std; is considered a bad practice.
More info:
std::map : https://en.cppreference.com/w/cpp/container/map
std::string: https://en.cppreference.com/w/cpp/string/basic_string
In c++, you need to be aware of the common concepts of compile time and run time. So in your example:
// newVarName declares new int with the name of the user input
If you mean something like this:
int name_dependant_on_user_input = value_from_user
This is impossible in c++, because the variable name, is a compile time thing. The user input happens at runtime, which is after compilation has completed. Something you could do, is map a string input to your user input, for eg.
std::unordered_map<std::string, int> user_vars;
std::string variable_name;
int variable_value;
cin >> variable_name;
cin >> variable_value;
user_vars[variable_name] = variable_value;
...
for (const auto& value_pair : user_Vars) {
std::cout << "User value for " << value_pair.first << " is " << value_pair.second;
}
im trying to get the data from a string variable and put it into its own place in a string vector but it saves each word as its own point in the vector.
i.e. "buy milk" will result in 0 being buy then 1 being milk not 0 being buy milk.
sorry for not knowing the proper terminology im really new to C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string input;
vector <string> Notes;
int SaveNoteOnLine = 0;
string output; //a var needed for specific situations, not used for all output
cout << "welcome to cmdnotes alpha v1.0\n";
while (true) {
cin >> input;
if (input == "-list") {
for (int i = 0; i < SaveNoteOnLine; i++) {
cout << Notes.at(i) << endl;
}
}
else {
Notes.push_back(input);
cout << "saved on line " << SaveNoteOnLine << endl;
SaveNoteOnLine++;
}
}
}
Use
getline(cin,input) inplace of cin>>input it will take whitespaces as input
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.
I'm a newbie with c++, and I tried googling a solution but every one I came across was so different from the issue I was facing so I couldn't figure it out. The problem I'm having is my "if" statements are completely ignored when I run the .exe from powershell.
https://pastebin.com/aE6MiQig
#include <iostream>
#include <string>
using namespace std;
int main()
{
string q;
string w;
string Bob;
string Emily;
{
cout << "Who is this? ";
cin >> q;
if (q == Bob)
{
cout << "Hey there bro. ";
}
if (q == Emily)
{
cout << "Hi friend :) ";
}
else
{
cout << "Oh hey " << q << ", how are you? ";
}
cin >> w;
cout << "Hey, that's " << w;
}
return 0;
}
When I input my name as "Bob" I should be seeing the message from the if statement "Hey there bro." but I am instead seeing the else statement, "Oh hey Bob, how are you?". Same goes when I input Emily. Only seeing the else statement.
I'm not getting any errors (running this in visual studio) so where am I messing this up?
Why not just compare directly to strings?
#include <iostream>
#include <string>
int main()
{
std::string q;
std::string w;
std::cout << "Who is this? ";
std::cin >> q;
if (q == "Bob") // note the quotation marks around Bob
{
std::cout << "Hey there bro. " << std::endl;
}
else if (q == "Emily") // note the quotation marks around Emily
{
std::cout << "Hi friend :) " << std::endl;
}
else
{
std::cout << "Oh hey " << q << ", how are you? ";
std::cin >> w;
std::cout << "Hey, that's " << w << std::endl;
}
return 0;
}
Also, you should avoid using namespace std because it leads to namespace pollution. Instead, you can just put std:: in front of string, cin, cout, and endl as I've done above, or include a using statement for each of those specifically, like this:
using std::string;
using std::cin;
using std::cout;
using std::endl;
std::string comes with its own operator==, comparing the string's contents.
string Bob;
string Emily;
Well, now you have created two strings, both using the default constructor, and so both are empty strings (i. e. they both would compare equal to "").
You need to assign them a value:
string Bob("Emily");
string Emily("Bob");
I deliberately assigned them inverse! Try this piece of code and you'll discover yourself that it is the content that is relevant for comparison, not the variable's name...
You obtain the value for string q from the user and compare it to string Emily or string Bob , neither of which have any values assigned.
The problem I'm having is my "if" statements are completely ignored when I run the .exe from powershell.
Your if statements are not being ignored instead you're comparing string q to "".
You can give string Bob and string Emily initial values:
#include <iostream>
#include <string>
int main()
{
std::string Bob = "Bob";
std::string Emily = "Emily";
std::string q;
}
This way you have something to compare the values you're getting from cin to:
#include <iostream>
#include <string>
int main()
{
std::string Bob = "Bob";
std::string Emily = "Emily";
std::string q;
std::cout<<"What is your name? ";
std::cin>>q; //Obtain value from cin
if(q == Emily){}//If q is Emily, then do something
}
You can read more about default variable values here and here.
I got a task from my teacher. I try some code but it confuses me a lot. So here's my code :
#include <iostream>
using namespace std;
char inputChecker [1000];
string source = "10110111000111001101110";
string detected;
int main(){
cout <<"Input:";
cin >> inputChecker;
for (int i=0;i<source.size();i++){
if (source[i]==inputChecker[0]){
cout <<"Data " <<inputChecker <<"is exist" <<endl;
}
else if (source[i]==inputChecker[i]){
cout <<"Data " <<inputChecker <<" isn't exist'" <<endl;
}
}
}
So ,my expectation output is ,when i input 10,it will result "Data 10 is exist". Without looping. I think it needed 2 kind of looping but i dont know where to loop.
My expectation output :
Input : 10
Data 10 is exist
Input : 25
Data 25 isn't exist
Thanks in advance :))
No need for loop
#include <iostream>
using namespace std;
int main() {
string source = "10110111000111001101110";
string input;
cin >> input;
if (source.find(input) != string::npos)
cout << input << " exists\n";
else
cout << input <<" doesn't exist\n";
}
Have a look at other useful std::string methods like find_first_of, find_last_of, etc.