I'm a beginner, so please excuse my silly mistakes.
I'm trying to get a specific output when I input a specific name using strings, but I keep getting an error that my name wasn't declared in the scope. I also want to be able to add different responses for different inputs.
I tried looking up how to use strings, and I tried all sorts of combinations, but I'm still confused as to what I did wrong.
I'm sorry if this doesn't make sense, I'm just really bad at explaining things.
#include <iostream>
#include <cmath>
#include <string>
int main() {
std::string firstname;
std::cout << "please state your name. \n";
std::cout << firstname;
std::cin >> firstname;
if (firstname == leo) {
std::cout << "oh, you.";
}
return 0;
}
First, std::cout << firstname; is a no-op since firstname is empty at that point.
Second, there is no name in your code. Is the error referring to leo? That should be wrapped in double-quotes since you meant it to be a string literal, not a variable.
Try something more like this:
#include <iostream>
#include <string>
int main() {
std::string firstname;
std::cout << "please state your name. \n";
std::cin >> firstname;
if (firstname == "leo") {
std::cout << "oh, you.";
}
else {
std::cout << "hello, " << firstname;
}
return 0;
}
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'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 am a c++ beginner and I am curious to why this does not work:
#include <iostream>
using namespace std;
int main ()
{
int firstname;
int lastname;
cout << "My name is " << firstname << lastname;
cin >> firstname >> lastname;
cout << endl;
return 0;
}
I want the output to simply be where the user inputs their first name and the last name and it turns out to be as follows:
Example:
My name is John Doe.
#include <string>
...
string firstname;
string lastname;
int values hold numbers. To store names, use strings.
cin >> firstname >> lastname;
cout << "My name is " << firstname << " " << lastname;
Then make sure to read the names before you print them. The cin and cout should be swapped. I've also added a space (" ") in the printout between the two variables.
#include <iostream>
#include <string> // so you can use string
using namespace std;
int main() {
string first;
string last;
cin >> first;
cin >> last; // getting input from using and storing it in last
cout << "My name is " << first << last << endl; // printing out "My name is and " and what you wrote for first and last
return 0;
}
cout << "My name is ";
cin >> firstname >> lastname;
cout << firstname << " " << lastname;
This should output a single line of:
My name is John Doe
Plus, strings of characters are stored in string types, not int types
So you'd have to include <string>, and change the ints to string
Name can be of int type change it to std::string
Here is the modified code will produce output as you want.
#include <iostream>
int main ()
{
std::string firstname;
std::string lastname;
std::cin >> firstname >> lastname;
std::cout << "My name is " << firstname<<" " << lastname<<"\n";
return 0;
}
Note that the you will have to add " " while printing if you want a white space between your first name and last name.
Try to take input using 'getline(cin,str); if your string contain white space too.
I would suggest you to not to use standard namespace i.e. using namespace std; while writing the code. For more detail please have a look of link provided below
Why is "using namespace std" considered bad practice?
First I would try to prompt the user to enter their first and last name. Or else how would they know what to enter? And using int type does not help at all because the user would be entering a string and not an integer. Try this ...
#include <iostream>
using namespace std;
int main() {
cout << "Pleas enter your first and last name." << endl;
string name;
cin >> name;
cout << "Hello " << name << endl;
return 0;
}
Make sure that the user knows what to input (first and last name) otherwise they will not know what to input. This is the output code you can use:
cout << "Please enter your first and last name." << endl;
So the full code should look something like this:
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string firstname;
string lastname;
cout << "Please enter your first and last name: " << endl;
cin >> firstname >> lastname;
cout << "My name is " << firstname << " " << lastname;
cout << endl;
return 0;
}
You are doing
int firstname;
int lastname;
meaning that you want to get an integer value, however you want a string. So, replace the int with std::string or string in your case. Also, remember to #include <string> to get the string functionality. After doing this, you should be able to input and return letters. :D
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string firstname;
string lastname;
cout << "My name is " << firstname << lastname;
cin >> firstname >> lastname;
cout << endl;
return 0;
}
Might I add that you generally should not use using namespace std; as it is considered bad practice, it also is not really necessary, you could just type std::.... using namespace std is used if you do not want to type the namespace name every time, but it's generally better to distinguish between which type of functions you want to use with the same names but in different namspaces. and using '\n' for a new line as well instead of endl. This is because endl takes more time to complete than \n.
I recommend to also include the namespace in your code if you are a beginner. In simple cases like printing strings its readable but a better practice if you're learning to include std::string, std::cin, and std::cout. In this case the :: just means to grab the keyword(right value) from its namespace(left value).
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"
I am teaching myself C/C++ at the moment, and I got the exercise (from the book I am reading) to write a program that could make an output like this:
Enter your first name: Flip
Enter your last name: Fleming
Here’s the information in a single string: Fleming, Flip
Using Structures. But my output comes out like this:
Enter your first name: Flip
Enter your last name: Fleming
Here’s the information in a single string: ,
Here is the code. It's fairly short and simple so it shouldn't be hard to read :)
#include <iostream>
#include <cstring>
using namespace std;
struct Person {
char* firstName;
char* lastName;
};
char* getName(void);
int main() {
Person* ps = new Person;
cout << "Enter your first name: ";
char* name;
name = getName();
ps->firstName = name;
cout << "Enter your last name: ";
char* lastname;
lastname = getName();
ps->lastName = lastname;
cout << "Here's the information in a single string: "
<< ps->lastName << ", " << ps->firstName;
delete ps;
delete name;
delete lastname;
return 0;
}
char* getName() {
char temp[100];
cin >> temp;
cin.getline(temp, 100);
char* pn = new char[strlen(temp) + 1];
strcpy(pn, temp);
return pn;
}
First, there's no such thing as C/C++. You're mixing them, which is wrong. Since you're using C++ headers/new/using, I'll assume you want C++, so here's how you fix your code:
replace all char* and char[] with std::string
get rid of dynamic allocation
So, some changes would be:
struct Person {
std::string firstName;
std::string lastName;
};
or
Person ps;
You are using:
cin >> temp;
cin.getline(temp, 100);
You probably overwrite what you already have with empty string at the end of a line.
Use just one of them.
If you'll stick with using cin >> you may consider setting width() to prevent buffer overflow.
First, the immediate problem is that you read twice from std::cin: first with operator>>, and then with getline. Pick one or the other.
But let's simplify your code a bit. There are simply too many sources of error. Pointers are tricky because they might point to the wrong thing, or you might forget to delete objects, or delete them twice. C-style char arrays as strings are bad because, well, they're not strings, and they don't behave like strings.
So let's use the standard library's string class:
#include <iostream>
#include <string>
struct Person {
std::string firstName;
std::string lastName;
};
std::string getName(void);
int main() {
Person ps;
cout << "Enter your first name: ";
std::string name = getName();
ps.firstName = name;
cout << "Enter your last name: ";
std::string lastname = getName();
ps.lastName = lastname;
cout << "Here's the information in a single string: "
<< ps.lastName << ", " << ps.firstName;
}
std::string getName() {
std::string temp;
std::getline(cin, temp);
return temp;
}
This is a fairly simple, almost mechanical substitution, basically just replacing char* by std::string, and removing the bits that are no longer necessary.
Of course, as pointed out in a comment, I've omitted all forms of error checking, which a real program should definitely do.
No no no, wayyyy too complicated. Use real C++ idioms. The program could be as simple as this:
#include <string>
#include <iostream>
int main()
{
std::string firstName, lastName;
if (!(std::cout << "Your first name: " &&
std::getline(std::cin, firstName) &&
std::cout << "Your last name: " &&
std::getline(std::cin, lastName) ))
{
std::cerr << "Error: unexpected end of input!\n";
return 0;
}
std::cout << "You are " << firstName << " " << lastName << ".\n";
}
As a variation on the theme, you could put each getline in a loop until the user inputs a non-empty line:
std::cout >> "Your first name: ";
for ( ; ; )
{
if (!(std::getline(std::cin, firstName))
{
std::cerr << "Error: unexpected end of input.\n";
return 0;
}
if (!firstName.empty())
{
break;
}
std::cout << "Sorry, please repeat - your first name: ";
}