cin >> int given a string assigns int to 0 - c++

The issue that I'm having is that if you input any string the cin will assign the int to 0. An interesting finding is that if you later take cin to a string you get the entire string you put in for the int. cin.fail() always returns true for some reason, even with cin.ignore(), etc and if( cin >> startingPosition ) also always returns true. So, how do I get it to catch an even recognize that it's a string and not an int? As in, how do I have it loop again if it is a string?
int getUserPosition(bool volatileCall = false) {
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
int startingPosition;
cin >> startingPosition;
while (startingPosition >= WIDTH || startingPosition < 0) {
cout << "Invalid slot." << endl << endl;
if (volatileCall) {
return -1;
}
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
cin >> startingPosition;
cout << startingPosition << endl;
}
return startingPosition;
}

you must save result from cin
isNumber = (cin >> startPosition);
the whole code will look like
int getUserPosition(bool volatileCall = false) {
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
int startingPosition;
bool isNumber = (cin >> startingPosition);
while(isNumber && (startingPosition >= WIDTH || startingPosition < 0)) {
cout << "Invalid slot." << endl << endl;
if (volatileCall) {
return -1;
}
cout << "Which slot do you want to drop the chip in (0-8)? " << endl;
isNumber = (cin >> startingPosition);
cout << startingPosition << endl;
}
return startingPosition;
}

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();
//...

why is my last else condition not executing correctly

why is it when I input anything other than int I get 0 is an even number, the plan was if the user enters something that's not an integer it should output invalid input
cout << "Enter an integer: ";
cin >> input;
if(input % 2 == 0) {
cout << input << " is an even "
"number" << endl;
}else if(input % 2 != 0) {
cout << input << " is an odd "
"number" << endl;
}else {
cout << "Invalid input!" << endl;
}
cin >> input is an operation that can fail, and if it fails the input variable does not contain a useful value. You can check whether it succeeded by converting cin to bool:
cin >> input;
if (!cin) {
cout << "Invalid input!" << endl;
} else if (input % 2 && input != 0) {
...
Or, since cin >> input returns the cin object again, this is equivalent:
if (!(cin >> input)) {
cout << "Invalid input!" << endl;
} else if (input % 2 && input != 0) {
...
Here's the code that works thanks to jtbandes
Exercise - Write a program to check whether a given number is ODD or Even
cout << "Even/Odd Program" << endl;
int input;
cout << "Enter an integer: ";
cin >> input;
if (!(cin >> input)) {
cout << "Invalid input!" << endl;
} else if(input % 2 == 0) {
cout << input << " is an even "
"number" << endl;
}else
cout << input << " is an odd "
"number" << endl;
return 0;
}

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.

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++ Address Book Array and Textfile

Sorry for the lack of previous explanation to my school's assignment. Here's what I'm working with and what I have / think I have to do.
I have the basic structure for populating the address book inside an array, however, the logic behind populating a text file is a bit beyond my knowledge. I've researched a few examples, however, the implementation is a bit tricky due to my novice programming ability.
I've gone through some code that looks relevant in regard to my requirements:
ifstream input("addressbook.txt");
ofstream out("addressbook.txt");
For ifstream, I believe implementing this into the voidAddBook::AddEntry() would work, though I've tried it and the code failed to compile, for multiple reasons.
For ostream, I'm lost and unsure as to how I can implement this correctly. I understand basic file input and output into a text file, however, this method is a bit more advanced and hence why I'm resorting to stackoverflow's guidance.
#include <iostream>
#include <string.h> //Required to use string compare
using namespace std;
class AddBook{
public:
AddBook()
{
count=0;
}
void AddEntry();
void DispAll();
void DispEntry(int i); // Displays one entry
void SearchLast();
int Menu();
struct EntryStruct
{
char FirstName[15];
char LastName[15];
char Birthday[15];
char PhoneNum[15];
char Email[15];
};
EntryStruct entries[100];
int count;
};
void AddBook::AddEntry()
{
cout << "Enter First Name: ";
cin >> entries[count].FirstName;
cout << "Enter Last Name: ";
cin >> entries[count].LastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
cout << "Enter Email: ";
cin >> entries[count].Email;
++count;
}
void AddBook::DispEntry(int i)
{
cout << "First name : " << entries[i].FirstName << endl;
cout << "Last name : " << entries[i].LastName << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
}
void AddBook::DispAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DispEntry(i);
}
void AddBook::SearchLast()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].LastName) == 0)
{
cout << "Found ";
DispEntry(i);
cout << endl;
}
}
}
AddBook AddressBook;
int Menu()
{
int num;
bool BoolQuit = false;
while(BoolQuit == false)
{
cout << "Address Book Menu" << endl;
cout << "(1) Add A New Contact" << endl;
cout << "(2) Search By Last Name" << endl;
cout << "(3) Show Complete List" << endl;
cout << "(4) Exit And Save" << endl;
cout << endl;
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
return 0;
}
int main (){
Menu();
return 0;
}
As it currently stands, I'm still stuck. Here's where I believe I should start:
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
//save first name
//save last name
//save dob
//save phone number
//save email
//exit
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
Somehow, during menu option 4 the array should dump the data into a .txt file and arrange it in a way that it can be easily imported upon reloading the program. I'm a little confused as to how I can store the array data from each character array into a .txt file.
Well first, if the input is coming from the file input, then instead of doing cin >> x you would have to do input >> x. If it's coming from standard input (the keyboard), then you can use cin.
Also, your else if statement should be something like this:
while (true)
{
// ...
else if (num == 4)
{
for (int i = 0; i < AddressBook.count; ++i)
{
AddBook::EntryStruct data = AddressBook.entries[i];
out << data.FirstName << " " << data.LastName
<< std::endl
<< data.Birthday << std::endl
<< data.PhoneNum << std::endl
<< data.Email;
}
}
break;
}