I have made a phone book and the function to add users. I want it to have numbers in front of every line, but I get the wrong number in front of each line. I have added code that prints out the numbers but it gives a big number that is the same on every line. I want it to print like this:
1 John Doe
2 Johnny Doe
3 Max Doe
Right now, it prints this instead:
1878003873 John Doe
1878003873 Johnny Doe
1878003873 Max Doe
I don't know where that number comes from.
void addContact()
{
string Fname, Lname, Address, Contact, list, name, Fname2, Lname2, Address2, Contact2;
int counter, number;
cout << "Enter First Name: ";
getline(cin, Fname);
cout << "Enter Last Name: ";
getline(cin, Lname);
cout << "Enter Address: ";
getline(cin, Address);
cout << "Enter Contact Number: ";
getline(cin, Contact);
ifstream asd("number.txt");
while (asd >> counter >> Fname2 >> Lname2 >> Address2 >> Contact2)
{
number = counter;
}
ofstream adb("number.txt", ios::app);
number = number + 1;
adb << number << " " << Fname << " " << Lname
<< " " << Address << " " << Contact << endl;
}
Suppose that you are adding your first user. What do you think that value of number is going to be then?
ifstream asd("number.txt");
while (asd >> counter >> Fname2 >> Lname2 >> Address2 >> Contact2)
{
number = counter;
}
Because it is your first user then while loop is never entered, so number is never initialised. Hence the garbage numbers you see. Once the first garbage number is there, then the code correctly adds one to each following number.
To fix just add this so that number always gets an initial value.
int counter, number = 0;
Not what you asked about but I think you should close your input file before you try to write the new user
ifstream asd("number.txt");
while (asd >> counter >> Fname2 >> Lname2 >> Address2 >> Contact2)
{
number = counter;
}
asd.close(); // stop reading and close the input file
ofstream adb("number.txt", ios::app);
...
Having a reading and a writing stream open simultaneously on the same file is not a good idea, even if it does seem to work in this case.
Related
I'm trying to write a C++ code that calculates a student's percentage grade.
This is a sample of what the output should look like
Enter student's first and last name: John Smith
Number of questions on the test: 40
Number of answers the student got correct: 31
John Smith 77.5%
Below is my own code. It allows me to enter the first line:
Enter student's first and last name:
but then it just exits and this is the feedback
return value 3221225620
Please, what am I doing wrong?
// Lab 3 percentage.cpp
// This program will determine the percentage
// of answers a student got correct on a test.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string name;
int numQuestions,
numCorrect,
studentName;
double percentage;
// Get student's test data
cout << "Enter student's first and last name: ";
cin >> studentName;
cout << "Number of questions on the test: ";
cin >> numQuestions;
cout << "Number of answers the student got correct: ";
cin >> numCorrect;
// Compute and display the student's % correct
percentage = (numCorrect / numQuestions) * 100;
// WRITE A STATEMENT TO COMPUTE THE % AND ASSIGN THE RESULT TO percentage.
cout << "The student: " << studentName << "has a test score of " << percentage << endl;
return 0;
}
cout << "Enter student's first and last name: ";
cin >> studentName;
studentName is an integer and you need to receive a string and above in your code you defined
string name;
so what you need to do is :
cin >> name;
but when you want to receive first name and last name, there is a space between them so instead of using cin, you need to use :
getline(cin, name);
and finally fix this :
cout << "The student: " << studentName << "has a test score of " << percentage << endl;
with :
cout << "The student: " << name << "has a test score of " << percentage << endl;
#include <iostream>
#include <string>
#include "Friend.h"
#include "Address.h"
using namespace std;
int main() {
string name = "";
string street = "";
string city = "";
string state = "";
long phone_number = 0000000000;
int zip_code = 00000;
int feet = 0;
int inches = 0;
cout << "What is your friends name: ";
cin >> name;
cout << "What street does he live on: ";
cin >> street;
cout << "What city does he live in: ";
cin >> city;
cout << "What state does he live in: ";
cin >> state;
cout << "What is his 10 digit phone number: ";
cin >> phone_number;
cout << "What is his zip code: ";
cin >> zip_code;
cout << "How tall is he in feet: ";
cin >> feet;
cout << "And how many inches: ";
cin >> inches;
return 0;
}
This is my code. The problem here is: after I enter my phone number, it just doesn't wait for an input any more. It will output the cout << statements that follow automatically and then terminate it self. I am not sure why this happens.
Could someone help me please?
The variable phone_number is of type long, which is the same as long int. This means that you can only enter numbers as input for phone_number.
The best guess why it doesn't work for you is that you enter the phone number as: XXX-XXXXXXX (with the dash). The "-" splits the input, and the numbers after the dash are passed on to the next input variable zip_code.
If you try input for phone number as: 1234567890, then it works fine. If you want to use the dash, then consider changing phone_number to type string.
As an aside, take input for your string-type variables using getline() instead of cin << so that the compiler will continue reading all input until the ENTER key is hit.
Each line of the text file has first name, last name, and a salary. Something along the lines of this:
john doe 4000
bob miller 9000
I want my program to take the first name, last name, and salary of each line and assign them to strings (or integers). I have tried this so far:
while (inFile){
inFile >> firstName;
inFile >> lastName;
inFile >> grossPay;
cout << firstName << " " << lastName << " " << grossPay << endl;
}
When it outputs the names and the salary, the last line of the text file gets output twice by the program. How can I fix this?
After reading your last line, inFile is still in a valid state.
It's only when it tries to read more that your test would fail, but control has already entered the loop an additional time.
You want to test after reading.
while ( inFile >> firstName >> lastName >> grossPay ){
// ^^ Now the test happens AFTER reading...
cout << firstName << " " << lastName << " " << grossPay << endl;
}
Here is the code in the main class where I am asking for input.
Class in(nameOfClass, numOfStudents);
for (int i = 0; i < numOfStudents; i++)
{
cout << "\nEnter the name of student " << i + 1 << ": ";
string studentName = "";
cin.ignore();
getline(cin, studentName);
cout << "\n ~ Enter the grades for " << studentName << endl;
cout << " ~ (Use this format: 3 - 100 100 100)" << endl;
cout << " ~ ";
string gradeLine = "";
getline(cin, gradeLine);
Student stu = Student(studentName, gradeLine); in .addStudent(i, stu);
cout << endl;
}
For the first run of the loop, the studentName reads in all the characters including spaces since I used getline(cin, studentName);. If I input "Andrew", then studentName will read in "Andrew".
However, for all further runs of the loops, if I input "Andrew" for the name of the student, the program stores "ndrew" into the studentName variable. I tried using cin.ignore(), cin.clear(), and cin.sync() in different places in the loop, but it stops the input and I need to enter a '\n' for it to to keep going and ask for the next student's information.
How do I clear the buffer after the loop is done so that my next run on the loop reads all the characters, but the loop does not pause and waits for the user to enter '\n'?
int x=0;
string fullname = "";
float salary;
float payincrease;
float newsal;
float monthlysal;
float retroactive;
while(x<3){
cout << "\n What is your full name?";
cin >> fullname;
cout << "\n What is your current salary? \t";
cin >> salary;
cout << "\n What is your pay increase? \t";
cin >> payincrease;
newsal = (salary*payincrease)+salary;
monthlysal = newsal/12.00;
retroactive = (monthlysal*6)-(salary/2);
cout << "\n" << fullname << "'s SALARY INFORMATION";
cout << "\n New Salary \t Monthly Salary \t Retroactive Pay";
cout << "\n \t" << newsal << "\t" << monthlysal << "\t" << retroactive;
x++;
}
My loop doesn't seem to stop for every time cin is asked, and instead instantly executes the loop 3 times on its own. How do I get it to stop when input is asked?
If the input stream isn't empty when you call cin, then cin uses the data already in the buffer instead of waiting for more from the user. You're using the extraction operator, so when cin is sending values to your variables, it skips leading whitespace in the buffer and stops on the next whitespace.
Put a breakpoint on this line:
cout << "\n What is your current salary? \t";
Run the program, and enter Bob Smith. When you hit the break point, hover your cursor over your string fullname. You'll see it stores only "Bob" not "Bob Smith". "Bob Smith" got put into the buffer, but when you use cin with the extraction operator, it skips any leading whitespace, puts the next value it finds into your variable, then stops on the next whitespace. To demonstrate this, try running this:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1,str2;
cin >> str1;
cin >> str2;
cout << str1 << " " << str2 << "\n\n";
return 0;
}
If you type in "Bob Smith", it will take your input only one time, even though you call cin twice. However, you'll see that both "Bob" and "Smith" got captured in the strings str1 and str2.
Therefore, you can conclude that cin stops populating your string fullname when it gets to the space between Bob and Smith. On your next call to cin, the buffer still contains "Smith", so instead of taking more input from the user, it attempts to fill your variable salary with "Smith". Obviously this isn't want you want to do. You can call flush and ignore on cin to wipe out the buffer before every time you use cin, or instead you could fix your logic and use getline to take in the full name, including spaces.
To fix your problem, all you need to do is use getline instead of cin >>, so replace this line:
cin >> fullname;
with this:
getline(cin,fullname,'\n');
Secondly, you're using a while loop to execute a set of actions a specific number of times. That's typically something you'd use a for loop for.
As an aside, you could also write tiny input validation loops that can help you debug or otherwise avoid attempting to put invalid input into your variables (such as "Smith" into a float). Something like this could work:
for(;;)
{
if(cin >> salary)
break;
cin.clear();
cin.ignore(INT_MAX,'\n');
}
Note that cin returns a value, so you can use it in an if statement. If it gets valid input, it will return true. If not, it will return false. To make it more explicit, you could also just use a normal call to cin without the if statement, and then check if cin.good(), which amounts to basically the same net effect. If you're not using Visual Studio and get an error about INT_MAX, you might need to #include limits.h to resolve it.
That occurs if you input a char where an int is expected.
Use cin.clear(); and cin.ignore(numeric_limits<streamsize>::max(), '\n'); to limit an input to int's only.
Other than that, it won't skip if the correct data type is put in.
#include <string>
#include <iostream>
#include <limits>
using namespace std ;
int main(void)
{
int x=0;
string fullname = "";
float salary;
float payincrease;
float newsal;
float monthlysal;
float retroactive;
while(x<3)
{
cout << "\n What is your full name?";
cin >> fullname;
cin.ignore( 1000, '\n' );
cout << "\n What is your current salary? \t";
cin >> salary;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "\n What is your pay increase? \t";
cin >> payincrease;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
newsal = (salary*payincrease)+salary;
monthlysal = newsal/12.00;
retroactive = (monthlysal*6)-(salary/2);
cout << "\n" << fullname << "'s SALARY INFORMATION";
cout << "\n New Salary \t Monthly Salary \t Retroactive Pay";
cout << "\n \t" << newsal << "\t" << monthlysal << "\t" << retroactive;
x++;
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
Check your variable types, I noticed mine accepting a digit instead of a character, had the same problem (not stopping, loop just kept going on).
> std::cin >> this->controls.button
> DETOX_NUMBER button; // (int)
Change to:
> char button;