How to read and store a string value in c++ [duplicate] - c++

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Why must type getline(cin, string) twice?
(5 answers)
Closed 9 months ago.
what's wrong
if I use the get line function only once in the character modifier function the compiler will ignore it
unless I call the function twice
why cant I use it only once?
I tried using other ways, it worked but I wanna understand this one
I'm now just writing random things so the add more details error messages go away
#include <iostream>
#include<string>
using namespace std;
class egybest
{
string link,m;
char sys, type, restart;
int s = 1, e = 1, date;
public:
string charmodifier()
{
//here
getline(cin, m);
getline(cin, m);
for (int x = 0; x <= m.size(); x++)
{
if (m[x] == ' ')
m[x] = '-';
}
return m;
}
~egybest()
{
system("cls");
cout << "do you want to restart the program? y:n;" << endl;
cin >> restart;
system("cls");
if (restart == 'y' || restart == 'Y')
egybest();
else if (restart == 'n' || restart == 'N')
{
system("exit");
}
}
egybest()
{
cout << "do you want to watch a movie or a series? 1:2;" << endl;
cin >> type;
system("cls");
if (type == '1')
linkmovie();
else if (type == '2')
series();
else
cout << "wrong input!" << endl;
}
void linkmovie()
{
cout << "enter the name of the movie:" << endl;
charmodifier();
cout << "enter the release date: " << endl;
cin >> date;
link = "start https://cape.egybest.cool/movie/" + m + "-" + to_string(date);
cout << endl;
system(link.c_str());
}
void series()
{
cout << "do you want it to open links for a particular season, particular episode or all seasons? s:e:a;"
<< endl;
cin >> sys;
system("cls");
if (sys == 'S' || sys == 's')
linkseason();
else if (sys == 'A' || sys == 'a')
linkall();
else if (sys == 'E' || sys == 'e')
linkepisode();
else
cout << "wrong input!" << endl;
}
void linkall()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int j = 1; j <= s; j++)
{
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(j) + "-ep-" + to_string(i);
system(link.c_str());
}
}
cout << endl;
}
void linkepisode()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(e);
cout << endl;
system(link.c_str());
}
void linkseason()
{
cout << "season No." << endl;
cin >> s;
cout << "episodes No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(i);
cout << endl;
system(link.c_str());
}
}
};
int main()
{
egybest egy;
return 0;
}```

The problem is that after entering an integer or a character as for example
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
//...
the input buffer contains the new line character '\n' that corresponds to the pressed Enter key.
So the following call of getline reads an empty string until the new line character is encountered.
In such a case before calling getline you need to remove the new line character from the input buffer like for example
#include <limits>
//...
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
charmodifier();
//...

Related

why does the getline() function does not work unless I call it twice in the function charmodifier [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Why must type getline(cin, string) twice?
(5 answers)
Closed 9 months ago.
what's wrong
if I use the get line function only once in the character modifier function the compiler will ignore it
unless I call the function twice
why cant I use it only once?
I tried using other ways, it worked but I wanna understand this one
I'm now just writing random things so the add more details error messages go away
#include <iostream>
#include<string>
using namespace std;
class egybest
{
string link,m;
char sys, type, restart;
int s = 1, e = 1, date;
public:
string charmodifier()
{
//here
getline(cin, m);
getline(cin, m);
for (int x = 0; x <= m.size(); x++)
{
if (m[x] == ' ')
m[x] = '-';
}
return m;
}
~egybest()
{
system("cls");
cout << "do you want to restart the program? y:n;" << endl;
cin >> restart;
system("cls");
if (restart == 'y' || restart == 'Y')
egybest();
else if (restart == 'n' || restart == 'N')
{
system("exit");
}
}
egybest()
{
cout << "do you want to watch a movie or a series? 1:2;" << endl;
cin >> type;
system("cls");
if (type == '1')
linkmovie();
else if (type == '2')
series();
else
cout << "wrong input!" << endl;
}
void linkmovie()
{
cout << "enter the name of the movie:" << endl;
charmodifier();
cout << "enter the release date: " << endl;
cin >> date;
link = "start https://cape.egybest.cool/movie/" + m + "-" + to_string(date);
cout << endl;
system(link.c_str());
}
void series()
{
cout << "do you want it to open links for a particular season, particular episode or all seasons? s:e:a;"
<< endl;
cin >> sys;
system("cls");
if (sys == 'S' || sys == 's')
linkseason();
else if (sys == 'A' || sys == 'a')
linkall();
else if (sys == 'E' || sys == 'e')
linkepisode();
else
cout << "wrong input!" << endl;
}
void linkall()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int j = 1; j <= s; j++)
{
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(j) + "-ep-" + to_string(i);
system(link.c_str());
}
}
cout << endl;
}
void linkepisode()
{
cout << "season No." << endl;
cin >> s;
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(e);
cout << endl;
system(link.c_str());
}
void linkseason()
{
cout << "season No." << endl;
cin >> s;
cout << "episodes No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
for (int i = 1; i <= e; i++)
{
link = "start https://cape.egybest.cool/episode/" + m + "-season-" + to_string(s) + "-ep-" + to_string(i);
cout << endl;
system(link.c_str());
}
}
};
int main()
{
egybest egy;
return 0;
}```
The problem is that after entering an integer or a character as for example
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
charmodifier();
//...
the input buffer contains the new line character '\n' that corresponds to the pressed Enter key.
So the following call of getline reads an empty string until the new line character is encountered.
In such a case before calling getline you need to remove the new line character from the input buffer like for example
#include <limits>
//...
cout << "episode No." << endl;
cin >> e;
cout << "enter the name of the show:" << endl;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
charmodifier();
//...

I've read a lot about the 2d array but I'm having troubles using it on my assignment

Here is the link to the assignment
I managed to get the majority of the project working except the void finalSales() function. I'm not too sure how to go about it with a one and two-dimensional array and display it accordingly. I have a midterm exam coming up next week and this chapter is included. I added some comments on what the functions do below:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
bool isPlaying = true, isPlaying_Two = true, isPlaying_Three = true, isLooping = true;
string salesPerson[6] = { "Jericho Rosales", "lisa Soberano", "Kim Chiu", "maja Salvador", "Katheryn Bern", "Daniel Padilla" },
items[3] = { "Washing Machine", "Refrigerator", "Music System" };
double table[6][3], totalSales[6] = {0};
int salesNum, productNum;
double saleAmount;
void Sales();
void person();
void prod();
void finalSales();
int main()
{
while (isLooping) {
Sales();
}
}
//main game
void Sales() {
while (isPlaying)
{
person();
if (salesNum > 0 && salesNum < 7) {
//cout << "debug " << salesPerson[salesNum - 1];//debug
cout << "\n";
while (isPlaying_Two)
{
prod();
if (productNum > 0 && productNum < 4) {
//cout << "debug " << items[productNum - 1];//debug
while (isPlaying_Three)
{
finalSales();
}
}
else
{
cout << "\n";
cout << "Input out of range, please try again\n";
cout << "\n";
}
}
}
else {
cout << "\n";
cout << "Input out of range, please try again\n";
cout << "\n";
}
}
}
//user selects which salesperson
void person() {
cout << "Sales Registry\n";
for (int i = 0; i < 6; i++)
{
cout << i + 1 << ". " << salesPerson[i] << "\n";
}
cout << "Select the Salesperson by typing his ordinal number: ";
cin >> salesNum;
//check if cin failed
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid entry, enter again ";
cin >> salesNum;
}
}
//user selects which product
void prod() {
for (int i = 0; i < 3; i++)
{
cout << i + 1 << ". " << items[i] << "\n";
}
cout << "Select the product by typing the product ordinal number: ";
cin >> productNum;
//check if cin failed
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid entry, enter again ";
cin >> productNum;
}
}
//get the sales amount(enter a random number in) and
//if the user wants to enter more sales it goes back to the beginning and asks again while remembering the previous values
//if not then the program adds up the amount (if there is more than one) and displays it accordingly to the salesperson and the product
void finalSales() {
string again;
cout << "Enter the sales amount: ";
cin >> saleAmount;
//check if cin failed
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid entry, enter again ";
cin >> saleAmount;
}
cout << "Do you want to enter more sales? Type y for yes and n for no: ";
cin >> again;
//check if cin failed
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid entry, enter again ";
cin >> saleAmount;
}
if (again == "y" || again == "Y") {
Sales();
}
else {
cout << "\n";
cout << "Salesperson" << "\t\t" << "Washing Machine" << "\t\t" << "Refrigerator" << "\t\t" << "Music system\n";
cout << "****************************************************************************************************";
cout << "\n";
for (int x = 0; x < 6; x++)
{
cout << salesPerson[x];
for (int y = 0; y < 3 ; y++)
{
cout << "\t\t\t" << table[x][y];
}
cout << "\n";
}
}
}
You need to return index from person() and prod() then pass them to finalSales. Also pass array to it and increase the amount of product by the saleAmount. And don't forget to make your bool variables false or you end up with infinite loop. Create two int variables in Sales(). Initialize them by returning the index from person() and the other one from product().
void finalSales(int idx1, int idx2,double table[6][3]) {
string again;
cout << "Enter the sales amount: ";
cin >> saleAmount;
table[idx1][ idx2] = saleAmount;
//check if cin failed
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid entry, enter again ";
cin >> saleAmount;
}
cout << "Do you want to enter more sales? Type y for yes and n for no: ";
cin >> again;
//check if cin failed
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid entry, enter again ";
cin >> saleAmount;
}
if (again == "y" || again == "Y") {
Sales();
}
else {
::isPlaying_Three = false;
::isPlaying_Two = false;
::isPlaying = false;
::isLooping = false;
cout << "\n";
cout << "Salesperson" << "\t\t" << "Washing Machine" << "\t\t" << "Refrigerator" << "\t\t" << "Music system\n";
cout << "****************************************************************************************************";
cout << "\n";
for (int x = 0; x < 6; x++)
{
cout << salesPerson[x];
for (int y = 0; y < 3; y++)
{
cout << "\t\t\t" << table[x][y];
}
cout << "\n";
}
}
}
That's for person() and the same for prod().
int person() {
cout << "Sales Registry\n";
for (int i = 0; i < 6; i++)
{
cout << i + 1 << ". " << salesPerson[i] << "\n";
}
cout << "Select the Salesperson by typing his ordinal number: ";
cin >> salesNum;
//check if cin failed
while (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid entry, enter again ";
cin >> salesNum;
}
return salesNum-1;
}
Don't forget to decrease index by 1.

Prompt User to Loop

I have created a Prompt User to Loop to restart the program however when I type anything including "y" it just goes prompts me with "Press any key to continue . . . " and then closes. Here's my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int Multiple1 = 0;
int Multiple2 = 0;
char again = 'Y';
while (again == 'y' || again == 'Y')
{
int Multiple1 = 0;
int Multiple2 = 0;
cout << "Input your first Multiple: " << endl;
cin >> Multiple1;
cout << "Your First Multiple is: " << Multiple1 << endl;
cout << "Input your second Multiple: " << endl;
cin >> Multiple2;
cout << "Your Second Multiple is: " << Multiple2 << endl;
for (int i = 1; i <= 100; i++)
{
if (i % Multiple1 == 0 && i % Multiple2 == 0)
cout << "FizzBuzz" << endl;
else
if (i % Multiple1 == 0)
cout << "Fizz" << endl;
else
if (i % Multiple2 == 0)
cout << "Buzz" << endl;
else cout << i << endl;
}
{
cout << "Restart? (y/n) ";
cin >> again;
}
system("pause");
return 0;
}
}
Thank you.
This is my first project and I am completely new to coding so I am not sure what to do.
Your return 0 is misplaced, it should be outside the while loop.
And you shouldn't put a bracket {} around your cin >> again.
{ // this bracket doesn't needed
cout << "Restart? (y/n) ";
cin >> again;
}
Just use bracket when it needed e.g. in for, if, function, etc. It will not make a compile error. But I think it makes you misread and think the while loop was closed.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int Multiple1 = 0;
int Multiple2 = 0;
char again = 'Y';
while (again == 'y' || again == 'Y')
{
int Multiple1 = 0;
int Multiple2 = 0;
cout << "Input your first Multiple: " << endl;
cin >> Multiple1;
cout << "Your First Multiple is: " << Multiple1 << endl;
cout << "Input your second Multiple: " << endl;
cin >> Multiple2;
cout << "Your Second Multiple is: " << Multiple2 << endl;
for (int i = 1; i <= 100; i++)
{
if (i % Multiple1 == 0 && i % Multiple2 == 0)
cout << "FizzBuzz" << endl;
else
if (i % Multiple1 == 0)
cout << "Fizz" << endl;
else
if (i % Multiple2 == 0)
cout << "Buzz" << endl;
else cout << i << endl;
}
{ //This bracket doesn't need.
cout << "Restart? (y/n) ";
cin >> again;
continue;
} // This bracket doesn't need.
system("pause");
return 0;
}
}

C++ Input Into Structure: _getch()

In C++, I'm trying to input movie's names and years of releasing and store them in a database/structure. Before I ask for the titles and years to be inputted. I have the user log on with credentials. In this case, the username is "rusty" and the password is "rusty".
The issue I'm having is the after the credentials are verified, the first movie title to input into the database/structure is skipped. I believe this has something to do with me using the _getch function, but I'm not totally sure.
My code is below. My output looks like this:
Please enter your username
rusty
Please enter your password
Access granted! Welcome rusty
Enter title: Enter year: (input movie year)
Enter title: (input movie title)
Enter year: (input movie year)
Enter title: (input movie title)
....
#include <iostream>
#include <string>
#include <sstream>
#include <conio.h>
using namespace std;
//function prototype
int username_and_pass();
#define NUM_MOVIES 6
struct movies_list{
string title;
int year;
}films[NUM_MOVIES];
// prototype with function declaration
void sort_on_title(movies_list films[], int n)
{
movies_list temp;
for (int i = 0; i < n - 1; i++)
{
if (films[i].title>films[i + 1].title)
{
temp = films[i];
films[i] = films[i + 1];
films[i + 1] = temp;
}
}
}// end of sort_on_title function
void printmovie(movies_list movie)
{
cout << movie.title;
cout << " (" << movie.year << ") \n";
}
void search_on_title(movies_list films[], int n, string title)
{
bool flag = false;
for (n = 0; n < NUM_MOVIES; n++)
{
if (films[n].title == title)
{
cout << "Title: " << films[n].title << endl;
cout << "Year of Release: " << films[n].year << endl;
cout << "\n";
flag = true;
}
}
if (flag == false)
cout << "Search on title not found!" << endl;
}// end of search_on_title function
void search_on_year(movies_list films[], int n, int year)
{
bool flag = false; // check on existence of record
for (n = 0; n < NUM_MOVIES; n++)
{
if (films[n].year == year) // display if true
{
cout << "Title: " << films[n].title << endl;
cout << "Year of Release: " << films[n].year << endl;
cout << "\n";
flag = true;
}
}
if (flag = false)
cout << "Search on title not found!" << endl;
}// end of search_on_title function
int menu()
{
int choice;
cout << " " << endl;
cout << "Enter 1 to search on titles " << endl;
cout << "Enter 2 to search on years " << endl;
cin >> choice;
cout << "\n";
return choice;
}// end of menu function
int username_and_pass()
{
string uName;
string password;
int value;
char ch;
cout << "Please enter your username\n";//"rusty"
cin >> uName;
cout << "Please enter your password\n";//"rusty"
ch = _getch();
while (ch != 13)//As long as the user doesn't press Enter
{//(enter is ASCII code 13) continue reading keystrokes from the screen.
password.push_back(ch);
cout << '*';
ch = _getch();
}
if (uName == "rusty" && password == "rusty")
{
cout << "\n\nAccess granted! Welcome " << uName << "\n\n" << endl;
value = 1
}
else
{
cout << "Invalid credentials" << endl;
value = 0;
}
return value;
}// end of username_and_pass function
int main()
{
string mystr;
int n;
string response;
int value = 0;
do
{
value = username_and_pass();
} while (value==0);
if(value==1)
{
for (n = 0; n < NUM_MOVIES; n++)
{
cout << "Enter title: ";
getline(cin, films[n].title);
cout << "Enter year: ";
getline(cin, mystr);
stringstream(mystr) >> films[n].year;
}
//sorts records
sort_on_title(films, NUM_MOVIES);
cout << "\nYou have entered these movies:\n";
for (n = 0; n < NUM_MOVIES; n++)
printmovie(films[n]);
//menu
int choice = 0;
choice = menu();
if (choice == 1)
{
string searchTerm;
cout << "What is the movie you want to search for? " << endl;
cin >> searchTerm;
cout << " " << endl;
search_on_title(films, NUM_MOVIES, searchTerm);
}
else
{
int searchTermYear;
cout << "What is the year you want to search for? " << endl;
cin >> searchTermYear;
cout << " " << endl;
search_on_year(films, NUM_MOVIES, searchTermYear);
}
cout << "Would you like to query the database again? (Y/N)" << endl;
cin >> response;
if (response == "Y" || "y")
{
choice = menu();
if (choice == 1)
{
string searchTerm;
cout << "What is the movie you want to search for? " << endl;
cin >> searchTerm;
cout << " " << endl;
search_on_title(films, NUM_MOVIES, searchTerm);
}
else
{
int searchTermYear;
cout << "What is the year you want to search for? " << endl;
cin >> searchTermYear;
cout << " " << endl;
search_on_year(films, NUM_MOVIES, searchTermYear);
}
}
}
return 0;
}
Flush all the content's of input buffer.
Please go to following link to flush contents of input buffer.
https://stackoverflow.com/a/7898516/4112271
I am not sure what causing you this problem.But can you try using cin.clear(). Place it before you ask for input of title.
cin.clear();
cout << "Enter title: ";
getline(cin, films[n].title);
cout << "Enter year: ";
getline(cin, mystr);
stringstream(mystr) >> films[n].year;

C++ my program reads backspace as a character

I am working with a c++ program, but I am stuck with annoying bug. The bug is that when i type the password, it counts backspace as a character so can I fix it? Here is the code.
#include <iostream>
#include <conio.h>
using namespace std;
int main() {
string password, username, lon, nu, np;
char c;
int StarNum = 0, humanproof;
cout << "Do you wanna create a user or login?";
cout << "\nLogin" << endl;
cout << "New" << endl;
cin >> lon;
if(lon=="login"){
goto login;
}
if(lon=="new"){
goto newa;
}
login:
cout << "Username: ";
cin >> username;
lol:
cout << "Password: ";
while (c != 13)
{
c = (char)getch();
if(c == 13) break;
StarNum++;
password += c;
cout << "*";
if (c == 127 || c == 8){
//go here to fix the problem
}
password = "";
goto lol;
}
}
if(username == "user" && password == "pass" || username == nu && password == np){
cout << "\nYou are logged in.";
goto options;
} else {
cout << "\nusername or password is wrong" << endl;
return 0;
}
return 0;
newa:
cout << "Username:";
cin >> nu;
cout << "password:";
cin >> np;
cout << "Type the number fourhoundred and twentie three too proof you are a human: ";
cin >> humanproof;
if(humanproof == 423){
cout << "The username is " << nu << endl;
for(int no = 0; no <= 100; no++){
cout << endl;
}
goto login;
return 0;
}
if(humanproof!=423){
cout << "wrong answer!";
return 0;
}
options:
int op;
cout << "\nwhat do you want to do?" << endl;
cout << "1. Calculator" << endl;
cout << "2. About"<< endl;
cout << "3. Just for fun" << endl;
cout << "4. Exit" << endl;
cin >> op;
if(op==1){
goto calculator;
}
if(op==2){
goto info;
}
if(op==3){
goto fun;
}
if(op==4){
return 0;
}
else{
cout << "you entered a invalid number. " << endl;
return 0;
}
calculator:
double n1, n2, sum;
int opa;
cout << "Choose a operation" << endl;
cout << "1. Addition/+" << endl;
cout << "2. Subscraction/-" << endl;
cout << "3. Multiplication/x" << endl;
cout << "4. Divsion/ /" << endl;
cin >> opa;
if(opa == 1){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 + n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 2){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 - n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 3){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 * n2;
cout << "the sum is " << sum;
return 0;
}
if(opa == 4){
cout << "enter number 1" << endl;
cin >> n1;
cout << "enter number 2" << endl;
cin >> n2;
sum = n1 / n2;
cout << "the sum is " << sum;
return 0;
}
if(opa > 4){
cout << "You entered a invalid number";
goto calculator;
}
info:
cout << "Created by Bergur 2013";
return 0;
fun:
cout << "You want an eyepad(ipad)?";
}
Your code already checks:
while (c != 13)
And prevent newline from being handled, do similar to what you need with the backspace character, whose number is 8
To fix your issue, before:
StarNum++;
Add:
if (c == 8 && StarNum > 0) {
StarNum--;
if (password.size () > 0)
password.resize (password.size () - 1);
continue;
}
Please format your code. Also, try to provide a minimal code which reproduce the problem, not the whole code.
Unrelated to your problem
Try not to use goto.
Do not use ASCII values, but use the char literals instead, i.e. use '\n' instead of 13.
Also, you can simply add an iother condition inside your while:
while (c != '\n' && c != ' ')