In c++, is it possible for me to make a loop, that asks the user to input information, and loop back to ask if they would like to keep adding information, until they dont. And store the values they typed into different parts of an array?
Ive been trying to use a while loop, but what happens is it will prompt if they want to add info, they select yes, they add it, if no, it puts into the terminal what they typed, but if I do yes twice, I just overwrite the first value, any way to correct this? I am quite new to programming and would appreciate any help, thank yo. (What I have is just a template to go off of, I know why it doesnt work, I also left out the preprocessor directives
#include <iostream>
#include <string>
using namespace std;
int main()
{
string add;
string name [100];
while (true)
{
cout <<"Would you like to add a name? Yes or No? \n";
getline(cin, add);
if (add == "yes" or add == "Yes")
{
cout<<"Enter a name\n";
getline(cin, name);
}
else if( add == "no" or add == "No")
{break;}
else
{
cout <<"sorry, that is not a valid response"<<endl<<endl;
}
}
cout<<name;
return 0;
}
I think trying to use pointers could work, but they have been confusing me haha. Any help or advice would be greatly appreciated, thank you.
Use of std::vector can make your life easier here. See a code snippet:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string add;
string name;
vector<string> names;
while (true)
{
cout <<"Would you like to add a name? Yes or No? \n";
getline(cin, add);
if (add == "yes" or add == "Yes")
{
cout<<"Enter a name\n";
getline(cin, name);
names.push_back(name);
}
else if( add == "no" or add == "No")
{
break;
}
else
{
cout <<"sorry, that is not a valid response"<<endl <<endl;
}
}
// printing contents
for(auto n:names)
cout << *n <<endl;
return 0;
}
Use array Name with Index instead of variable name when store information like this
#include <iostream>
#include <string>
using namespace std;
int main()
{
string add;
string name [100];
int index = 0; //Index Location of Array
while (true)
{
cout <<"Would you like to add a name? Yes or No? \n";
getline(cin, add);
if (add == "yes" or add == "Yes")
{
cout<<"Enter a name\n";
getline(cin, name[index]); // write name with index to insert value in particular index
}
else if( add == "no" or add == "No")
{break;}
else
{
cout <<"sorry, that is not a valid response"<<endl<<endl;
}
}
//loop here to output all value of name as mention above
cout<<name;
return 0;
}
Related
I am trying to make a basic choose-your-own-adventure style game by developing a basic system by which the program takes user char input and makes a decision using if-else statements to append strings in a certain pattern. In the following program I have tried to use strcat after a set of conditions to yield different output, but my outputs keep failing miserably. Any help someone could offer would be incredible.
#include <iostream>
#include<cstring>
#include<string>
#include<iomanip>
#include<ios>
#include<limits>
using namespace std;
int main()
{
char str1[50]= "F*ck";
char str2[50]= "You";
char str3[50]= "Me";
char answer[50];
cout<< "Do you like rock music yes or no?";
cin>> answer;
if (answer== "no"){
cout<< strcat(str1,str2);
} else (answer== "yes");{
cout<< strcat(str1,str3);
}
return 0;
}
When you use the == operator to compare C-style strings, you're actually comparing the addresses, not the contents, of the strings, which is not helpful in this case. Try using the strcmp() library routine instead, and you'll probably get a lot farther with what you're trying to do.
You can't compare the contents of C-style strings using operator==. You need to use strcmp() instead:
if (strcmp(answer, "no") == 0)
Also, else (answer== "yes");{ is wrong too. Not only because of the comparison issue, but also because you are missing a required if, and have an erroneous ;. It should be else if (strcmp(answer, "yes") == 0){ instead.
That being said, you really should be using std::string instead of char[], eg:
#include <iostream>
#include <string>
using namespace std;
int main() {
const string str1 = "F*ck";
const string str2 = "You";
const string str3 = "Me";
string answer;
cout << "Do you like rock music yes or no?";
cin >> answer;
if (answer == "no"){
cout << str1 << str2;
} else if (answer == "yes"){
cout << str1 << str3;
}
return 0;
}
if (answer== "no") You're comparing the memory address of answer and the string literal "no", so that condition is false
You should use strcmp() like this:
if(strcmp(answer, "no") == 0)
Also, your else has the wrong syntax. You should use else if
Change that to:
else if (strcmp(answer, "yes") == 0)
{
std::cout<< strcat(str1,str3);
}
Or even better, throw C-style string out of the window and use std::string instead.
#include <iostream>
#include <cstring>
#include <string>
#include <iomanip>
#include <ios>
#include <limits>
// using namespace std; is bad
int main()
{
std::string str1{"F*ck"};
std::string str2{"You"};
std::string str3{"Me"};
std::string answer;
std::cout<< "Do you like rock music yes or no?";
std::cin>> answer;
if (answer == "no")
{
std::cout<< (str1 + str2);
}
else if(answer == "yes")
{
std::cout << (str1 + str3);
}
return 0;
}
I was able to rewrite the program and it now works. Gonna be real helpful for a text-based choose your own adventure game. The new program is as follows:
#include <iostream>
#include<cstring>
#include<string>
using namespace std;
int main() {
char str1[50]= "F*ck";
char str2[50]= " You";
char str3[50]= " Me";
char answer[50];
cout<< "Do you like rock music (yes or no)?"<<endl;
cin>> answer;
if (strcasecmp(answer,"no") == 0){
cout<< strcat(str1,str2)<<endl;
} else if (strcasecmp(answer,"yes") == 0){
cout<< strcat(str1,str3)<<endl;
} else {
cout<< strcat(str1," off")<<endl;
}
return 0;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
bool exit = true;
bool wrongssn = false;
string menu;
cout << "To add a record, type add.\n";
cout << "To find someone by SSN, type find by ssn\n";
cout << "to display all records, type display all\n";
while (exit == true) {
cin >> menu;
if (menu == "add") {
cout << "ye";
}
if (menu == "find by ssn") {
cout << "Type the SSN you wish to search by";
int ssn;
cin >> ssn;
if (!cin) {
cout << "invalid choice, retry.\n";
}
}
im trying to get my second if statement to print out, but when I run the program, if I type "find by ssn", it will not print anything and keep asking me for keyboard input until I manually close out of the program.
This is because when you do cin>>menu, then menu stores find and not find by ssn because taking string input using cin stops after it encounters a whitespace. Instead use std::getline.
Syntax:
std::getline(std::cin, menu);
That's the code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main()
{
string name = "lol";
int score = 0;
vector<string>names;
vector<int>scores;
bool choose = true;
for (int l = 0; name != "stop"; ++l) {
cin >> name >> score;
if (name == names[l]) choose = false;
if (choose == true) {
names.push_back(name);
scores.push_back(score);
}
else cout << "error, name already used" << endl;
choose = true;
}
}
When I run the program, and I type a name followed by a score, it says: "debug assertion failed: vector subscription out of range".
Why? And how do I eliminate this error?
You try get element that doesn't exist. First you need push something to
vector<string> names;
or do check if names is empty:
if (!names.empty())
if(name == names[l])
choose = false;
also looking what you want achieve, it's seems that you have anyway wrong code, you only look at the last name you have added. So to help you a bit this solution works better:
int main()
{
string name;
vector<string> names;
while (cin >> name && name != "stop")
{
bool choose = true;
for (auto i : names)
{
if (name == i)
choose = false;
}
if (choose)
{
names.push_back(name);
}
else cout << "error, name already used" << endl;
}
}
my functions output_all, add_item, and remove_item are all getting this error from the main.cc file. What am I missing? I assumed this was pretty straight forward, but obviously I messed it up. I'll include my files below. Thank you in advance for any help!
main.cc
#include <iostream>
#include <string>
#include <cstdlib>
#include "basket.h"
using namespace std;
int main(){
int choice;
string item;
cout << "Would you like to: \n\n 1.See List \n 2.Add an Item \n 3.Remove an item \n 4.Exit \n\n Please Enter a number: ";
cin >> choice;
if (choice == 1){
output_all(cout);
}
else if (choice == 2){
cout << "Please enter the item you would like to add to the list: ";
cin >> item;
add_item(item);
}
else if (choice == 3){
cout << "Please enter the name of the item you would like to remove: ";
cin >> item;
remove_item(item);
}
else if (choice == 4){
exit(1);
}
else {
main();
}
return (0);
}
basket.h
#include <iostream>
#include <string>
using namespace std;
class basket{
public:
//function will output all of the items currently in the list
void output_all(ostream& fout);
//Function will allow user to add item to list
void add_item(const string& item);
//function will remove item from list after checking that item exists in the list
void remove_item(const string& item);
// accessor method to access the string name
string get_name();
private:
//string variable used for storing thr list
string name;
};
basket.cc
#include <iostream>
#include <string>
#include "basket.h"
using namespace std;
void basket::output_all(ostream& fout){
fout << name;
}
void basket::add_item(const string& item){
name = name + " " + item;
}
void basket::remove_item(const string& item){
int num = name.find(item);
name.erase(num, item.length());
}
string basket::get_name(){
return (name);
}
I can see output_all(), add_item(), remove_item() are non static member of basket class. So output_all(cout) should be called from an object like: basketObj.output_all(cout);
Well, you are calling functions like output_all, add_item, remove_item in your main. There's no such functions in your program. Hence the [obvious] error.
If you tried to call member functions of class basket, then you should have declared an object of type basket and used a completely different syntax (member access syntax). Your favorite C++ book will have plenty of explanations and examples of this.
BTW, it is illegal to manually call main function in C++. You have to learn to use cycles to achieve what you are trying to do with that recursive call to main.
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"