How to read in a String with white space in C++ [duplicate] - c++

This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 3 years ago.
so I'm working on a homework problem for my CS175 C++ course. We have a homework assignment where we have to make a shorting hat, kinda like what's in Harry Potter. I've got 99% of the code down, however the thing that is tripping me up is how to read in a string with white space.
We need to be able to input full names so obviously just using std::cin >> won't work. The problem is that I can't seem to get any of the methods to work that I've tried so far.
This is my code:
#include <iostream>
#include <string>
int main()
{
int NumStudents;
std::string NameStudents;
int StartValue;
int House;
std::string HouseName;
int NumCornfolk = 0;
int NumEsophagus = 0;
int NumBob = 0;
//How many students are there?
std::cout << "How many students are there? \n";
std::cin >> NumStudents;
for (StartValue = 0; StartValue < NumStudents; StartValue++) {
std::cout << "Please enter the name of the next student. \n";
std::cin >> NameStudents; \\**THE PROBLEM IS HERE**
//Assings the House
House = rand() % 100 + 1;
if (House <= 19) {
HouseName = "Cornfolk! \n";
NumCornfolk++;
}
else if (House > 19 && House < 50) {
HouseName = "Esophagus! \n";
NumEsophagus++;
}
else if (House >= 50) {
HouseName = "Bob! \n";
NumBob++;
}
std::cout << NameStudents << " got " << HouseName << std::endl;
}
//Prints Results
std::cout << "Number of Students in each House: \n";
std::cout << "Cornfolk:" << NumCornfolk << " Esophagus:" << NumEsophagus << " Bob:" << NumBob;
}
The line of code that reads std::cin >> NameStudents; is what's causing the problem. I've seen methods that say to use something along the lines of "std::cin.getline (name,256);" but cin.getline throws an error at the period and won't compile.
Being able to read in the names correctly is only 2/11 points, so it's not that big of a deal, but I would like to know why the suggested methods are not working here.
Thank you. This question is different from ones asked before mods.

Use std::getline, like this:
std::getline(std::cin, NameStudents);
Here's an example from https://en.cppreference.com/w/cpp/string/basic_string/getline:
std::string name;
std::cout << "What is your name? ";
std::getline(std::cin, name);
std::cout << "Hello " << name << ", nice to meet you.\n";

Related

Re run a c++ program based on user input or condition

I'm learning c++ and as an exercise with arrays and user input, I'm trying to write a simple poker application.
Since I'm at the begin of this course, all I know about the c++ language is that the execution of the code is demanded to the main() function. I've write some lines of code that is the base of the final app, it works fine for now. I want to implement a loop to re run the app based on the user input and on a condition that for the scope of the app will be the amount of th fish variable quantity after every execution. How I can achieve this? Another question is about the use of random elements from an array. Is there any good reference where I can learn how to do this?
This is my code:
#include <iostream>
using namespace std;
int main(){
string name;
int bet;
int fish = 100;
char seed[4][10] = {"hearts","clubs","diamonds","spades"};
int cards[9] = {2,3,4,5,6,7,8,9,10};
std::cout << "Welcome in PokerBash! Please enter your name:" <<std::endl;
std::cin >> name;
std::cout << "Your name is " << name <<std::endl;
std::cout << "You have a credit of:" << fish <<std::endl;
std::cout << "Please enter your bet:" <<std::endl;
std::cin >> bet;
std::cout << "Your cards are " << seed[2] << " " << cards[3] << " " << seed[1] << " " << cards[7] <<std::endl;
std::cout << "Your credits after this bet:" << fish - bet <<std::endl;
return 0;
}
You can do a loop that stops if the user wants to or fish is less than 0 by making a while loop that depends on some boolean playing that is initially true. So if one of the two events happen, set playing to be false and the loop stops:
int main() {
//variables
bool playing = true;
while (playing) {
int fish = 100;
//poker game
if (fish < 0) { //no money
playing = false;
}
else {
char input;
std::cout << "would you like to play again? (y/n): ";
std::cin >> input;
if (input != 'y') {
playing = false;
}
}
}
}
as you can see, this repeats until I enter something that isn't 'y':
would you like to play again? (y/n): y
would you like to play again? (y/n): y
would you like to play again? (y/n): n
to choose a random element from an array you would use the utilities from <random> like their std::mersenne_twister_engine. To get a random element from an array you would basically just need create a random number and use that as the arrays index:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937_64 engine(rd());
std::uniform_int_distribution<int> distribution(0, 8);
int cards[9] = { 2,3,4,5,6,7,8,9,10 };
while (true) {
std::cout << cards[distribution(engine)] << '\n';
}
}
some important things from here:
std::random_device rd;
std::mt19937_64 engine(rd());
is done only once (never in a loop). It is for initializing your pseudo random generator engine.
std::uniform_int_distribution<int> distribution(0, 8);
adds a distribution. Note that, because your int cards[9] has 9 elements, the range has to go from 0 to 8 as arrays start at 0and end at their size - 1, as you might probably already know. :)
Running this you can see it randomly prints out the card numbers from 2 to 10:
2
10
7
9
2
4
9
10
8
9
8
6
8
2
10
These are your helping points to implement further. I add some more things I noticed about your code but are not necessary to the question itself.
You should note that you should not use namespace std - you can read here why.
Also, instead of:
char seed[4][10] = { "hearts","clubs","diamonds","spades" };
use:
std::string seed[4] = { "hearts","clubs","diamonds","spades" };
To use std::string include the <string> header.
you wrote std::cin >> name; but this doesn't work for strings with spaces, like look here:
Welcome in PokerBash! Please enter your name:
Stack Danny
Your name is Stack
To get the full name, use
std::getline(std::cin, name);
Try this,
#include <iostream>
using namespace std;
int main()
{
string name;
int bet;
int fish = 100;
char seed[4][10] = {"hearts", "clubs", "diamonds", "spades"};
int cards[9] = {2, 3, 4, 5, 6, 7, 8, 9, 10};
while (1)
{
std::cout << "Welcome in PokerBash! Please enter your name ( Enter q to quit ):" << std::endl;
std::cin >> name;
if(name == "q")
exit(0);
std::cout << "Your name is " << name << std::endl;
std::cout << "You have a credit of:" << fish << std::endl;
std::cout << "Please enter your bet:" << std::endl;
std::cin >> bet;
std::cout << "Your cards are " << seed[2] << " " << cards[3] << " " << seed[1] << " " << cards[7] << std::endl;
std::cout << "Your credits after this bet:" << fish - bet << std::endl;
}
return 0;
}

How do I swap a pre defined array element using an index?

I'm trying to swap two array elements that are initialized strings (see code below), I thought i knew how to do it but the way I tried doesn't seem to be working. We're not allowed to use the function "swap" that I've seen on many other forum sights with a similar question as mine. Therefore I've used a temporary index variable to swap them but that doesn't seem to be working. Not sure how to fix it and make it work, so my question is how do I do it.
I'm pretty new to programming so the answer may not be as evident to me yet. I've been staring at this for a while and still can't see it, I also tried asking on reddit but they didn't give me a very concise or helpful answer. If you could help me out as to why it wont swap the elements that would be great and if you see any other bugs or improvements I could make please let me know, your feedback is greatly appreciated, thank you!
Code:
#include <iostream>
using namespace std;
void printArray(string names[]) {
for (int i = 0; i < 7; i++) {
cout << names[i] << " ";
}
}
int main() {
int x = 0, a, b;
string answer, name1, name2;
string index;
string names[7] = {"John", "Dave", "Jim", "Amanda", "Kelsey", "Don", "Jennifer"};
printArray(names);
while (x < 1) {
cout << endl << "Do you want to swap students? " << endl;
cin >> answer;
if (answer == "Yes" || answer == "yes") {
cout << "Who would you like to swap?" << endl;
cin >> name1;
for(a = 0; a < 7; a++) {
if (names[a] == name1) {
cout << "Yes, " << name1 << " is in the line." << endl;
}
}
cout << "Who would you like to swap " << name1 << " for?" << endl;
cin >> name2;
for(b = 0; b < 7; b++) {
if (names[b] == name2) {
cout << "Yes, " << name2 << " is in the line!!" << endl;
index = names[a];
names[a] = names[b];
names[b] = index;
printArray(names);
}
}
} else {
cout << endl << "Thanks, please behave now, students!" << endl;
x++;
}
}
return 0;
}
More context:
Print out the current class line-up (i.e., the current contents of the array, in order).
Present the user with a prompt asking if they would like to swap 2 students.
If they say yes, proceed to step 3.
Ask the user for the names of the two students to be swapped.
If the two students are both in the array, swap their positions in the array. If either student is not in the class, print an error message on the console, e.g. "Sorry, you have to pick 2 students who are in the line!".
No matter the outcome of step 4, return to step 1.
While searching for name1 ,the loop runs till 7 no matter if its found or not which messes with your swapping task:
index = names[a]; //a=7
names[a] = names[b]; //a=7
names[b] = index;.
Use break:
if (names[a] == name1) {
cout << "Yes, " << name1 << " is in the line." << endl;
break;
}
The value of a is always 7 while swapping is being done! So it is not working.

Nested loops in C++ and user input

Pretty new here to programming, and I have an assignment where I need to achieve the following:
ask for total amount of people
get each of their names
allow user to enter up to 5 scores for each person
if there are less than 5 scores for a given person, inputting -100 will stop it
So far I have written this:
#include <iostream>
using namespace std;
int main() {
string personName;
int totalPerson, personScoreCounter;
double personGrade, personGradeTotal;
cout << "Input total amount of people: ";
cin >> totalPerson;
for (int person = 1; person <= totalPerson; person++)
{
cout << "Input name for person " << person << ": ";
getline(cin, personName);
cin.ignore();
while ( (personGrade != -100) && (personScoreCounter <= 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
if (personGrade >= 0 && personGrade <= 100) // valid range of scores
{
personGradeTotal += personGrade;
personScoreCounter++;
}
else
{
cout << "Input only scores from 0-100" << endl;
}
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
}
}
// calculate averages and other stuff in here.
return 0;
}
After getting their name, only the last cout inside the while loop seems to execute first, then it starts from the top and so on until the for loop hits the end depending on totalPerson. I know I'm missing a few things in here, probably in the order of operations and also the way I am executing my loops, but I just can't see it. Could any of you guys with experience in the language please give me any pointers as to what's happening here and how I can fix it? Thank you.
Inside your while group, you only want to use your cout line once (at the beginning looks good).
Your first check should be for ==-100 or similar, since as it is now, you'll get a "Input only scores from 0 to 100" message if you enter -100.
You should keep a cin.ignore(); call after each use of cin >> VARIABLE, since then you will drop the EoL character.
Example code:
#include <iostream>
using namespace std;
int main() {
int totalPerson;
cout << "Input total number of people: ";
cin >> totalPerson;
cin.ignore();
for (int person = 1; person <= totalPerson; person++)
{
int personScoreCounter=0;
double personGrade = -1, personGradeTotal=0;
string personName;
cout << "Input name for person " << person << ": ";
std::getline(cin, personName);
while ( (personGrade != -100) && (personScoreCounter < 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
cin.ignore();
if (personGrade == -100) {
break;
} else if (personGrade >= 0 && personGrade <= 100) {
personGradeTotal += personGrade;
personScoreCounter++;
} else {
cout << "Input only scores from 0-100" << endl;
}
}
// calculate averages and other stuff in here.
double avg = personGradeTotal / personScoreCounter;
cout << "Avg = " << avg << endl;
}
return 0;
}
Some of your variables also needed to move inside the for loop.
Additionally I changed the limits on the personScoreCounter to [0:4] rather than [1:5] - this way you can use it for averaging more easily.
You might also try cin.getline() instead of getline(std::cin , ... ):
int max_length = 30;
std::cin.getline(personName, max_length, '\n'); // \n is option termination.
This allows whitespaces in the input also.
http://www.cplusplus.com/reference/istream/istream/getline/

Program will not run while statements message [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am making a game and I want it to only run if player consents by saying PLAY but it won't run. Here is my code:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int balance = 500;
char start;
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! " << endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
while(start == 'PLAY') {
cout << "Your beginning numbers are!" << endl;
}
}
A char is a single character, like 'P'. If you expect the user to enter a full string, you want to use std::string. Additionally, you probably want to simply check if the user entered the string you wanted - not while - unless you want to prompt again at the end of your game.
Corrected code would be:
std::string start;
// ...
std::cin >> start;
if (start == "PLAY") {
// play the game
}
start is a char and not an array of char. You are only storing one letter in start
Change that, and also change 'PLAY' to "PLAY". Consider using a std::string instead.
Example of what you can do:
int balance = 500;
char start[256];
bool started = false;
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! " << endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
if (!strcmp(start, "PLAY")) { // #include <cstring>
started = true;
}
while(started) {
cout << "Your beginning numbers are!" << endl;
}
Or with using std::string:
int balance = 500;
string start;
bool started = false;
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! " << endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
if (start == "PLAY") {
started = true;
}
while(started) {
cout << "Your beginning numbers are!" << endl;
}
change char start; to char start[100];
and while(start == 'PLAY') to while(start == 'PLAY')
Here is the final code
int balance = 500;
char start[100];
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! "<< endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
while(!strcmp(start,"PLAY")) {
cout << "Your beginning numbers are!" << endl;
}
You are trying to take in as input a string, but storing using a character.
use
char start[SIZE];
Also are u sure comparing with 'PLAY' is being done in the right way? Use " for strings. Better to use string functions.

How can I use 2D array in C++ using Visual Studio?

I'm new to this site and programming in C++ language this semester.
I have been really trying for 2 days and have asked classmates but they do not know either. A classmate said to use the 2D arrays but I don't know what that is and my professor has not gone over 2D arrays.
I am stuck and would really appreciate help.
The input file contains this:
Plain_Egg 1.45
Bacon_and_Egg 2.45
Muffin 0.99
French_Toast 1.99
Fruit_Basket 2.49
Cereal 0.69
Coffee 0.50
Tea 0.75
idk how to display all the "users" orders
Basically a receipt, like he orders this and how many, then ask "u want anything else?", then take the order number and how many again, THEN at the end give back a receipt that looks like this
bacon_and_eggs $2.45
Muffin $0.99
Coffee $0.50
Tax $0.20
Amount Due $4.14
Here is my code:
// Libraries
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <cmath>
using namespace std;
//structures
struct menuItemType {
string itemName;
double itemCost;
};
// Prototypes
void header();
void readData(menuItemType menu[]);
void Display(menuItemType menu[]);
int main() {
header();
menuItemType menu [8];
readData(menu);
Display(menu);
//system("pause");
return 0;
}
void header() {
char c= 61;
for (int i=0; i < 64; i++) {
cout << c;
}
cout << c << endl;
cout << endl;
cout << "Breakfast Menu" <<endl;
for (int i=0; i < 64; i++) {
cout << c;
}
cout << "" << c << endl;
cout << endl;
}
void readData(menuItemType item[]) {
int i=0;
ifstream in;
in.open("input.txt");
cout << fixed << setprecision(2);
while(!in.eof()) {
in >> item[i].itemName >> item[i].itemCost;
++i;
}
}
void Display(menuItemType item[]) {
int choice = 0, quantity = 0;
double total = 0.0, totalF = 0.0, tax = 0.0;
char exit = 'y';
int j = 1, z = 1, i = 1;
//the Menu
for (int i=0; i<8; i++){
cout << j << ". " << setw(18) << left << item[i].itemName << "$" << setw(10) << item[i].itemCost << endl;
j++;
}
cout << endl;
while(exit == 'y' || exit == 'Y') {
cout << "Please Enter your Selection or 0 to Exit : ";
cin >> choice;
if(cin.fail()) {
cout << "*******Invalid selection*******" << endl;
cin.clear();
cin.ignore(1000,'\n');
} else if (choice==0) {break; }
else {
cout<< "Enter Quantity: ";
cin>> quantity;
if (quantity==0) { break;}
else {
choice--;
total += (quantity * item[choice].itemCost);
tax = (total * .05);
totalF = total + tax;
cout << endl;
}
cout << endl;
cout << "======================================================" << endl;
cout << item[choice].itemName << "\t\t" << item[choice].itemCost << endl;
cout << "======================================================" << endl;
cout << "Do you want to continue (Y/N): ";
cin >> exit;
}
}
}
First off, you don't need a two dimensional array for this! You already have a one dimensional array of a suitable structure, as far as I can tell: Something which stores the name of the object and its price. What is somewhat missing is how many objects are currently in the array and how much space it has. If you want to go with the content of the entire array, make sure that you objects are correctly initialized, e.g., that the names are empty (this happens automatically, actually) and that the prices are zero (this does not).
I'm not sure if it is a copy&paste errors but the headers are incorrectly included. The include directives should look something like this:
#include <iostream>
The actual loop reading the values doesn't really work: You always need to check that the input was successful after you tried to read! Also, using eof() for checking that the loop ends is wrong (I don't know where people pick this up from; any book recommending the use of eof() for checking input loops is only useful for burning). The loop should look something like this:
while (i < ArraySize && in >> item[i].itemName >> item[i].itemCost)
++i;
}
This also fixes the potential boundary overrun in case there is more input than the array can consume. You might want to consider using a std::vector<Item> instead: this class keeps track of how many elements there are and you can append new elements as needed.
Note that you didn't quite say what you are stuck with: You'd need to come up with a clearer description of what your actual problem is. The above is just correcting existing errors and readjusting the direction to look into (i.e., forget about two dimensional arrays for now).