C++ value updating/ignoring - c++

So I have this
int main(){
string input;
string lastName;
string firstName;
int age;
int streetNum;
string streetName;
string town;
string zipCode;
float balance;
Update(lastName, firstName, age, streetNum, streetName, town, zipCode, balance);
}
and here is the function Update
void Update(string &lastname, string &firstname, int &age, int &streetnum, string &streetname, string &town, string &zipcode, float &balance){
cout << "Update the following, enter nothing to leave the same: " << endl;
string input;
cout << "Last name: ";
getline(cin, input);
if (input != "\n") { lastname = input; }
cout << "First name: ";
getline(cin, input);
if (input != "\n") { firstname = input; }
cout << "Age: ";
getline(cin, input);
if (input != "\n") { age = atoi(input.c_str()); }
cout << "Street number: ";
getline(cin, input);
if (input != "\n") { streetnum = atoi(input.c_str()); }
cout << "Street name: ";
getline(cin, input);
if (input != "\n") { streetname = input; }
cout << "Town name:";
getline(cin, input);
if (input != "\n") { town = input; }
cout << "ZipCode: ";
getline(cin, input);
if (input != "\n") { zipcode = input; }
cout << "Balance: ";
getline(cin, input);
if (input != "\n") { balance = atof(input.c_str()); }
}
My goal is to update the value or skip to the next value if the input is '\n'.
Once running and the program calls Update, it prints out "Last Name: First Name: " on the same line without letting the user input anything into lastname. I have no idea why it does this. Any tips or clues to directions to go in would be helpful.

getline() doesn't wait for user input. I believe unless you're told to use getline() you may want to use cin. Which would look as such:
cout<< "Lastname: ";
cin>>input;
if(input != " ")
{
lastname= input;
}
The only problem I foresee is that you won't be able to use '\n' as your condition for your if statements. In the above example I used a space as my skip character.

Related

Why is fullName not displaying name after space

The final cout is not displaying the cin fullName:
int main()
{
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName; //this final cout is not displaying the cin fullName
system("pause>0");
}
cin does not work with spaces in the input, the rest of your input is in the buffer.
Try using getline like this:
int main()
{
string fullName;
cout << "Type your full name:" ;
getline(cin,fullName);
cout << "Your name is: " << fullName;
system("pause>0");
}
This way it will save into your variable everything until it hits a \n.

Functions declared in header file gives not in scope error

I am working on a project which has no globally defined variables, or class objects or structs in it. I have a bunch of variables defined in the main of Voter.cpp and have different databse functions defined in VoterDB.cpp with the declarations made in VoterDB.h
VoterDB.h ---> VoterDB.cpp
|
|
|
Voter.cpp
Voter.cpp
#include <iostream>
#include <stdlib.h>
#include "VoterDB.h"
using namespace std;
class Voter {
public:
private:
};
int main(int argc, char *argv[])
{
string lastname="";
string firstname="";
int age=0;
int stnum=0;
string street="";
string town="";
string zip="";
float amtdonated=0;
cout << ">: ";
string command;
getline (cin, command);
while(command != "Quit"){
if(command=="New"){
cmd_new(lastname,firstname,age,stnum,street,town,zip,amtdonated);
} else if(command=="Update"){
cmd_update(lastname, firstname, age, stnum,street,town,zip);
} else if(command=="View"){
cmd_view(lastname,firstname,age,stnum,street,town,zip,amtdonated)
} else if(command=="Donate"){
} else if(command=="Report"){
}
}
}
VoterDB.cpp
#
include < iostream > #include < stdlib.h > #include < string > #include "VoterDB.h"
using namespace std;
void cmd_new(string & lastname, string & firstname, int & age, int & stnum, string & streetname, string & town, string & zip, float & amtdonated) {
cout << "\nEnter First Name\n";
cout << ">: ";
getline(cin, firstname);
cout << "\nEnter Last Name\n";
cout << ">: ";
getline(cin, lastname);
cout << "\nEnter Age\n";
cout << ">: ";
stringstream(cin, age);
cout << "\nEnter Street Number\n";
cout << ">: ";
stringstream(cin, stnum);
cout << "\nEnter Street Name\n";
cout << ">: ";
getline(cin, streetname);
cout << "\nEnter Town\n";
cout << ">: ";
getline(cin, town);
cout << "\nEnter Zipcode\n";
cout << ">: ";
getline(cin, zip);
amtdonated = 0.0;
return;
}
void cmd_update(string & lastname, string & firstname, int & age, int & stnum, string & streetname, string & town, string & zip) {
string input = "";
cout << "\nEnter Y or N\n";
cout << "Change First Name? (" << firstname << ")\n";
cout << ">: ";
if (getline(cin, input) == "Y" || getline(cin, input) == "y") {
cout << "\n>: ";
getline(cin, firstname);
input = "";
}
cout << "\nChange Last Name? (" << lastname << ")\n";
cout << ">: ";
if (getline(cin, input) == "Y" || getline(cin, input) == "y") {
cout << "\n>: ";
getline(cin, lastname);
input = "";
}
cout << "\nChange Age? (" << age << ")\n";
cout << ">: ";
if (getline(cin, input) == "Y" || getline(cin, input) == "y") {
cout << "\n>: ";
stringstream(cin, age);
input = "";
}
cout << "\nChange Street Number? (" << stnum << ")\n";
cout << ">: ";
if (getline(cin, input) == "Y" || getline(cin, input) == "y") {
cout << "\n>: ";
stringstream(cin, stnum);
input = "";
}
cout << "\nChange Street Name? (" << streetname << ")\n";
cout << ">: ";
if (getline(cin, input) == "Y" || getline(cin, input) == "y") {
cout << "\n>: ";
getline(cin, streetname);
input = "";
}
cout << "\nChange Town? (" << town << ")\n";
cout << ">: ";
if (getline(cin, input) == "Y" || getline(cin, input) == "y") {
cout << "\n>: ";
getline(cin, town);
input = "";
}
cout << "\nChange Zipcode? (" << zip << ")\n";
cout << ">: ";
if (getline(cin, input) == "Y" || getline(cin, input) == "y") {
cout << "\n>: ";
getline(cin, zip);
input = "";
}
return;
}
void cmd_view(string & lastname, string & firstname, int & age, int & stnum, string & streetname, string & town, string & zip, float & amtdonated) {
cout << firstname << " " << lastname << ", " << age << "\n"
cout << stnum << " " << streetname << "\n"
cout << town << " " << zip << "\n"
cout << "Amount Donated: $" << amtdonated;
return;
}
VoterDB.h
#ifndef VOTERDB_H
# define VOTERDB_H
# include < iostream > #include < stdlib.h > #include < string >
using namespace std;
class VoterDB {
public:
static void cmd_new(string lastname, string firstname, int age, int stnum, string streetname, string town, string zip, float amtdonated);
static void cmd_update(string lastname, string firstname, int age, int stnum, string streetname, string town, string zip);
static void cmd_view(string lastname, string firstname, int age, int stnum, string streetname, string town, string zip, float amtdonated);
private:
};
#endif
makefile
##
Specifiy the target
all: Voter
# Specify the object files that the target depends on# Also specify the object files needed to create the executable
Voter: Voter.o VoterDB.o
g++Voter.o VoterDB.o - o Voter.exe
# Specify how the object files should be created from source files
VoterDB.o: VoterDB.cpp
g++ - c VoterDB.cpp
Voter.o: Voter.cpp
g++ - c Voter.cpp
# Specify the object files and executables that are generated# and need to be removed to re - compile the whole thing
clean:
rm - f * .o Voter.exe
My issue is that whenever I attempt to compile this i get the error
$ make
g++ -c Voter.cpp
Voter.cpp: In function ‘int main(int, char**)’:
Voter.cpp:28:66: error: ‘cmd_new’ was not declared in this scope
cmd_new(lastname,firstname,age,stnum,street,town,zip,amtdonated);
^
Voter.cpp:30:61: error: ‘cmd_update’ was not declared in this scope
cmd_update(lastname, firstname, age, stnum,street,town,zip);
^
Voter.cpp:32:67: error: ‘cmd_view’ was not declared in this scope
cmd_view(lastname,firstname,age,stnum,street,town,zip,amtdonated)
^
makefile:15: recipe for target 'Voter.o' failed
make: *** [Voter.o] Error 1
I have tried different combinations of declaring the different cmd_* functions as static, and as VoterDB::cmd_* but none of these have fixed the issue so far.
edit: i changed the function calls to VoterDB::cmd_* and switched the functions from static void to void. but I now get an error message
Voter.cpp:32:76: error: cannot call member function ‘void VoterDB::cmd_view(std::__cxx11::string, std::__cxx11::string, int, int, std::__cxx11::string, std::__cxx11::string, std::__cxx11::string, float)’ without object
VoterDB::cmd_view(lastname,firstname,age,stnum,street,town,zip,amtdonated)
This answer should be deleted as a typo, as NathanOliver said. I'm writting it just to clarify you because you requested it.
To call a static member function of a class you must provide the name of the class.
So, in main(), instead of
cmd_new(lastname,firstname,age,stnum,street,town,zip,amtdonated);
use
VoterDB::cmd_new(lastname,firstname,age,stnum,street,town,zip,amtdonated);

Phone number lookup within text file

Basically My Program Goal is that i have a file containing 4 telephone numbers
it would Look Like this
Harry Keeling (555)123-4567
Frank James (555)123-8901
Arthur Paul (555)987-4567
Todd Shurn (555)987-8901
What my program is doing right now is prompting the user for the name and last name and iterates through the file to see if their is a match if their is a match the phone number is saved in the variable phone number if their isnt a match the program outputs error right now my program is doing what is susposed to do but after each match is found the program is susposed to prompt do you want to continue looking up numbers y or n if it is a yes it is susposed to loop through the file again but basically my program isnt working and i have no idea why my code
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void lookup_name(ifstream&, string&); // prototype
int main()
{
ifstream myfile;
string phonenumber;
string choice;
lookup_name(myfile, phonenumber);
if (phonenumber == " ") {
cout << "Error" << endl;
}
else {
cout << "The Telephone Number you Requested is" << phonenumber << endl;
cout << "Do you Want to look up another name in the directory?" << " " << "<Y/N" << endl;
cin >> choice;
if (choice == "Y")
lookup_name(myfile, phonenumber);
}
}
void lookup_name(ifstream& myfile, string& phonenumber)
{
string fname;
string lname;
string name1, name2, dummy, choice;
myfile.open("infile.txt");
cout << "What is your first name" << endl;
cin >> fname;
cout << "What is your last name" << endl;
cin >> lname;
for (int i = 0; i < 4; i++) {
myfile >> name1 >> name2;
if (fname + lname == name1 + name2) {
myfile >> phonenumber;
myfile.close();
if (choice == "Y")
{
continue;
}
else {
myfile >> dummy;
}
}
}
}
You need to add a loop inside of main() itself to prompt the user to continue, and you need to fix the mistakes in your lookup_name() function.
Try something more like this instead:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <limits>
using namespace std;
bool lookup_name(istream&, const string&, string&); // prototype
int main()
{
ifstream myfile("infile.txt");
string name, phonenumber, choice;
do
{
cout << "What is the name? ";
getline(cin, name);
if (!lookup_name(myfile, name, phonenumber)) {
cout << "Error" << endl;
}
else {
cout << "The Telephone Number you Requested is '" << phonenumber << "'" << endl;
}
cout << "Do you want to look up another name in the directory (Y/N)? ";
cin >> choice;
cin.ignore(numeric_limits<streamsize_t>::max(), '\n');
if ((choice != "Y") && (choice != "y"))
break;
myfile.seekg(0);
}
while (true);
return 0;
}
bool lookup_name(istream& myfile, const string& name, string& phonenumber)
{
string line, fname, lname;
while (getline(myfile, line))
{
istringstream iss(line);
if (iss >> fname1 >> lname)
{
if (name == (fname + " " + lname))
return getline(iss, phonenumber);
}
}
return false;
}

Read string from console along with whitespaces

I want to read a string from cin until the return key is pressed. What's wrong with the following code? The output repeatedly says "Invalid response found, please enter again: " even when i enter single words.. I've updated the code..
int readInt() {
int num;
while (!(std::cin >> num)) {
std::cout << "Invalid response found, please enter again: ";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return num;
}
string readString() {
string str;
while (std::getline(std::cin, str) && std::cin.fail()) {
std::cout << "Invalid response found, please enter again: ";
std::cin.clear();
std::cin.ignore();
}
return str;
}
DVD_Node* addNewDvd(DVD_Node *head) {
DVD_Node* temp = new DVD_Node;
int new_id = getNewID(head);
temp->id = new_id;
cout << "\n\n-- Add a new DVD to your collection --";
cout << "\n\nEnter movie name: ";
temp->title = readString();
cout << "\n\nEnter duration in minutes: ";
temp->duration = readInt();
cout << "\n\nEnter movie year: ";
temp->year = readInt();
cout << "\n\nEnter movie actor 1 name: ";
temp->actor1 = readString();
cout << "\n\nEnter movie actor 2 name: ";
temp->actor2 = readString();
temp->next = head;
changes_remaining = 1;
cout << "\n\nYour DVD Data has been added successfully.";
return temp;
}
The below test is not correct if you want to detect error :
std::getline(std::cin, str) && std::cin.fail()
Indeed, because getline return the input, you want to detect null input or errors with :
std::getline(std::cin, str) == 0 || std::cin.fail()

Unable to Count Number of Digits as the Input

My Program: To get input from the user about personal details and then output the information.
My Problem: The program is unable to count the number of digits as the input for Phone Number field. It accepts more than 10-digits as an input for the phone number.
My Goal: To check the input for 'Phone Number' and make sure that the number is 10-digits.
My Code:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
class Personal_Details
{
public:
void setFirstName (string newFirstName);
void setLastName (string newLastName);
void setBirthdate (int newBirthday);
void setEMail (string newEMail);
void setPhoneNumber (int newPhoneNumber);
void QUESTIONS();
string getFirstName();
string getLastName();
string getEMail();
int getPhoneNumber();
int getBirthdate();
private:
string FirstName;
string LastName;
string EMail;
int PhoneNumber;
int Birthdate;
};
void Personal_Details :: setFirstName (string newFirstName)
{
FirstName = newFirstName;
}
void Personal_Details :: setLastName (string newLastName)
{
LastName = newLastName;
}
void Personal_Details :: setBirthdate (int newBirthdate)
{
Birthdate = newBirthdate;
}
void Personal_Details :: setEMail (string newEMail)
{
EMail = newEMail;
}
void Personal_Details :: setPhoneNumber (int newPhoneNumber)
{
PhoneNumber = newPhoneNumber;
}
string Personal_Details :: getFirstName()
{
return FirstName;
}
string Personal_Details :: getLastName()
{
return LastName;
}
int Personal_Details :: getBirthdate()
{
return Birthdate;
}
string Personal_Details :: getEMail()
{
return EMail;
}
int Personal_Details :: getPhoneNumber()
{
if (PhoneNumber>12)
{
cout <<"INVALID. Program will now close.";
}
system ("PAUSE");
return PhoneNumber;
}
void Personal_Details :: QUESTIONS()
{
cout << "A.) Enter the following details:-" << endl <<endl;
cout << "First Name: ";
getline (cin, FirstName);
cout << endl;
cout << "Last (Family) Name: ";
getline (cin, LastName);
cout << endl;
cout << "Birthdate: ";
cin >> Birthdate;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "Email Address: ";
getline (cin, EMail);
cout << endl;
cout << "Phone Number: ";
cin >> PhoneNumber;
cout << endl;
cout<< FirstName <<" "<< LastName << endl
<<"Birthdate: "<< Birthdate << endl
<<"Email ID: "<< EMail << endl
<<"Phone Number: "<< PhoneNumber << endl;
}
int main()
{
Personal_Details NewContact;
cout << "- Add New Contact Information -" << endl << endl;
cout << "Note: Please type in only intergers (numbers) for 'Birthdate' and 'Phone Number' field. Also, phone number should be less than/or equal to 10 digits." << endl;
cout << "Else, this program will terminate abruptly." << endl << endl;
NewContact.QUESTIONS();
cout << endl << endl;
cout << "Press Any Key to Exit.";
cin.ignore();
cin.get();
return 0;
}
Please can you review and check why I am not able to input a real 10-digit phone number? I am new to C++, so I am unable to figure out a solution. Thanks for your help!
You are storing the phone number as an int, but the range of integers is –2,147,483,648 to 2,147,483,647; entering a 10 digit number outside of that range results in overflow and may be what is crashing your program.
You may want to read in the phone number as a string, check each character for validity, and process it however you need to (e.g.: a variable for area code, a variable of 7 digit number, reject out of range input and re-prompt).