C++ reset cin and cout - c++

Ok so I have 3 functions that all represent a question that I need to answer. My first question is working with cin and cout, and is broken into parts. The problem is that after one part finishes, another part automatically takes the remainder of the input in the first part rather than asking for a new input.
My problems lay in
//part B
char state[30];
cout << "Enter a sentence: " << endl;
cin.read(state, 15);
cout << "The sentence entered was:\n";
cout.write(state, cin.gcount());
cout << endl;
and
//part E
char charArray[12]; //creates an array of 12
cout << "Enter some characters: " << endl;
cin.getline(charArray, 12, 'y');
cout << "Your characters are: " << charArray << endl;
Where whatever I enter in part b gets used in part e. I have tried using clear, ignore, and flush but to no avail. Also, the original input gets used in my other functions, as well.
My main is set up like this:
int main()
{
question1();
question2();
question3();
}
How am I able to enter a fresh input to use in each part and each function?

Related

I am making a quiz-like program. I already wrote the string answer ="George Washington". but when the user inputted the answer, it's wrong

answer = "George";
cout << "\t\t\t\t\t Who was the first President of United States?" << endl;
cout << "";
cout << "";
cout << "Congrats " << player1_name << " (Player1). Now, type in your answer:";
cin >> player1_answer;
if (player1_answer == answer){
cout << "check";
}else{
cout << "x";
}
This is my code. But when the user inputted the answer as exactly as what was written in the answer variable, it outputs 'x'. But if the user inputted the same answer excluding the space between "George" and "Washington", it outputs 'check'. What should I do so that the program will accept the space in the answer inputted by the user?
I tried searching the web but I can't understand a thing. So please help me
You can simply use getline instead of cin. cin reads the user input up until the first whitespace character (most commonly newlines or spaces), but getline will read user input until they hit enter. Because of this, if you want to get user input that includes spaces, you should use getline (or something similar) instead of cin.
Instead of
cin >> player1_answer;
you should use
getline(cin, player1_answer);
By using getline, the full user input ("George Washington") get assigned to the variable player1_answer. With cin, only "George" was being used, because it stopped listening for input after the first space.
Here is a full, working code example:
#include <iostream>
using namespace std;
string answer = "George Washington";
string player1_name = "Steve";
string player1_answer;
cout << "\t\t\t\t\t Who was the first President of United States?" << endl;
cout << "";
cout << "";
cout << "Congrats " << player1_name << " (Player1). Now, type in your answer:";
getline(cin, player1_answer); //Enter "George Washington"
if (player1_answer == answer){
cout << "check";
}else{
cout << "x";
}
//"check"
return -1;

what is the problem in my file handling program?

I have written the following code
switch (number) {
case 1:
int accountnumber[20];
char firstname[20], lastname[20], balance[20];
cout << "please enter the account number of the user " << endl;
cin.getline(accountnumber, 20);
cout << "please enter the first name of the user " << endl;
cin.getline(firstname, 20);
cout << "please enter the last name of the user " << endl;
cin.getline(lastname, 20);
cout << "please enter the balance of the user " << endl;
cin.getline(balance, 20);
ofstream myfile(" data.txt");
myfile << accountnumber;
myfile.close();
int accountnumber1[20];
ifstrean.obj("data.txt");
obj.getline(accountnumber1, 20);
cout << "data is" << accountnumber1;
obj.close();
}
It is showing the following errors
no matching function for call to 'std::basic_istream<char>::getline(int[20], int) '
expected unqualified-id before'.' token
What are the mistakes that I am doing?
The problem is "accountnumber[20]" on line 4 is an integer array and you pass it to cin.getline on line 10, when it expects a char array instead. Since you're using a char array for numeric values such as balance, you might wanna consider making your account number into a char array as well.
int accountnumber[20];
char firstname[20],
lastname[20], balance[20];
becomes
char accountnumber[20], firstname[20], lastname[20], balance[20];
The formatting on your code is also really unconventional, you might want to stick to something more common for making it easier for anyone to read it.

How do I validate input without exiting my do while loop?

I'm working on a program that prompts the user to select from 3 different options by inputing an integer from 1-3 (4 to quit). I need to write a code that validates that the input is an integer, and reprompts them if it is not an integer. Here's the basic idea of my code (it is too long to post in entirety).
do
{
cout << "Menu: Please select one of the following options:" << endl;
cout << " 1 - Drop a single chip into one slot." << endl;
cout << " 2 - Drop multiple chips into one slot." << endl;
cout << " 3 - Drop 5 chips into each slot." << endl;
cout << " 4 - Quit the program." << endl;
cout << "Enter your selection now: ";
cin >> first_input;
}while (first_input!=4)
I then have multiple if statements that execute expressions based on which option the user chooses. I also prompt them to enter other integer values later in the code.
How do I send the user back to the menu, if the user inputs fails to input an integer and instead inputs characters? Constraints: Cannot use continue or break
Thanks in advance.
If you want to go back to the start in case of non-integer input, perhaps something like this would work?
// Insert after "cin >> first_input;"
if (cin.fail()) {
// Handle non-int value.
// Clear error flag.
cin.clear();
// Empty buffer up to next newline.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// Complain & restart.
cout << "Invalid input. Please try again." << endl;
continue;
}
What this does is clear the error flag, purge the buffer, and go back to the start. cin.ignore() doesn't explicitly need to be passed std::numeric_limits<std::streamsize>::max() as its first parameter; however, in case of error, I prefer to do so to make sure that the erroneous input is gone. Note that std::numeric_limits is defined in the standard header <limits>, and requires its inclusion.
You are looking for the continue keyword.
do
{
cout << "Menu: Please select one of the following options:" << endl;
cout << " 1 - Drop a single chip into one slot." << endl;
cout << " 2 - Drop multiple chips into one slot." << endl;
cout << " 3 - Drop 5 chips into each slot." << endl;
cout << " 4 - Quit the program." << endl;
cout << "Enter your selection now: ";
cin >> first_input;
//lets say if user enters value out of range. then want to show menu again.
if(first_input > 4) {
cout << "Invalid input "<<endl;
continue;
}
// you can do other stuff here.
// ...
}while (first_input!=4)
You can try using goto label.
do{
label:
// your code
if(check) goto label;
}while(check);

Weird Text File Output and Writing Issues

In my code:
int newEntry()
{
string input;
Client person;
char response = 'y';
//create file object and open file
fstream customer("customer.dat", ios::out | ios::app);
if (!customer)
{
cout << "Error opening file. Program aborting." << endl;
return 0;
}
do
{
cout << "Enter person information:" << endl << endl;
cout << "Name: " << endl;
getline(cin, input);
strcpy(person.name, input.c_str());
cout << endl << "Street Adress (And Apartment Number):" << endl;
cin >> person.address1;
getline(cin, input);
strcpy(person.address1, input.c_str());
cout << endl << "City, State, Zipcode: " << endl;
cin >> person.address2;
getline(cin, input);
strcpy(person.address2, input.c_str());
cout << endl << "Phone: " << endl;
cin >> person.phone;
getline(cin, input);
strcpy(person.phone, input.c_str());
cout << endl << "Account Balance: " << endl;
cin >> person.acctBal;
//input validation to ensure a non neg number
cin.ignore();
cout << endl << "Last Payment: " << endl;
cin >> person.lastPay;
//input validation to ensure a non neg number
customer.write(reinterpret_cast<char *>(&person),
sizeof(person));
cout << endl << "Do you want to enter another record? (Enter Y for Yes, N
for No) " << endl;
cin >> response;
cout << "_______________________________________________" << endl << endl;
if (toupper(response) == 'Y')
{
cin.ignore();
}
} while (toupper(response) == 'Y');
customer.close();
return 1;
}
It seems as though the block:
cout << endl << "Street Address (And Apartment Number):" << endl;
cin >> person.address1;
getline(cin,input);
strcpy(person.address1, input.c_str());
and its neighboring address 2 prompt (identical) are causing bad output to the file when
customer.write(reinterpret_cast<char *>(&person),sizeof(person));
is used to write to the file. The output is missing the very first word . For example if "211 Harvey Road" was entered, 211 would be cut off. Another example, if "Harvey Road" was entered, than it seems as though "harvey" is cut off. When (in another function) the file is read, the structure of arrays is missing the beginning, as well as the file.
On top of that, in the textfile, this is the data being written to it:
Frank Palmasani ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ Harvey Road ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ Haven, Alabama ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ 504617772 ÌÌÌÌ èŽ# èŽ#James Harris ni ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ Street AVEN ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ China. Alabama ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ 546457474 ÌÌÌÌ ð? ð?
As you can see, where the Ì are popping up is where the file and program are somehow losing the first word. I have tried everything I can think of to fix this problem, hopefully someobody else has ran into a similar problem.
I have tried changing methods of saving the data held in the structure of arrays to the file, but found that I couldn't read from the file in one large grouping. In my text book, the method I used to read out to the file is used so that is the one I believe I should follow.
However, I am considering writing each one separately on each line, and saving it precisely in the order so that I can read it in the same order, saving it to a structure of vectors. Again, I'd I would like to avoid that but would love to hear your opinion on the matter whether if you are able to help me here or not.
In case you needed it, here is my structure:
const int NAME_SIZE = 51, ADDR_SIZE = 51, PHONE_SIZE = 14;
struct Client
{
char name[NAME_SIZE];
char address1[ADDR_SIZE];
char address2[ADDR_SIZE];
char phone[PHONE_SIZE];
double acctBal;
double lastPay;
};
Your output file looks like that because you are doing a raw dump of the Client struct. So there will be 51 bytes written for name, 51 for address1, etc. Regardless of string length.
You need to properly write each field individually.
customer << input.name << endl;
customer << input.address1 << endl;
etc.....
cout << endl << "Street Adress (And Apartment Number):" << endl;
cin >> person.address1;
getline(cin, input);
strcpy(person.address1, input.c_str());
You're getting the first token, in the case you mentioned 211 and putting it in address1, then getting the rest of the line and replacing what was in address1 with it. That's where your 211 went.
You should open the file in binary mode if your intent is to write/read entire structures as a binary blob like this. If you want to store the data as text use std::string, avoid the strcpy mess, and write/read each member individually on their own ines.

Getting string length for morse code convertor keeps looping

working on one of my first programming assignments, a text to morse (and back) convertor, but for whatever reason when I introduce a piece of text with a space between words my programme goes into an endless loop and crashes. Any ideas? Sorry if this description sucks, still getting my head around programming lingo.
this is the piece of the program that isn't functioning properly:
{
string user_input;
cout << "----------------------------------------" <<endl
<< "Text to Morse Mode" << endl
<< "Enter text for conversion : "<<endl;
cin >> user_input;
cout << endl << endl << user_input << " converts to : ";
unsigned int str_lenght;
str_lenght=user_input.size();
cout << endl;
for (i=0;i<str_lenght;i++)
{
find_string=0;
while (find_string < stop_string)
{
if (user_input[i]==text[find_string][0])
{
count=1;
cout << morse[find_string] << " ";
break;
}
find_string = find_string+1;
}
}
cout << endl << endl << endl;
if (count==0)
cout << endl << " an error was encountered " << "\a" << endl ;
}
stop_string isn't defined anywhere from what I see. In order to break the loop via incrementing you need to define stop_string. Also find_string = find_string+1; could be shortened to find_string++
First you haven't defined stop_string variable anywhere. First define it or use another variable. If it is string length intent to use here, use the str_length you have created.
Secondly if you want to input spaces in between your words, use getline instead of cin. cin delimits space character.