The program, is basically sussposed to iterate a file containing the elements
Harry Keeling (202)806-4830
Frank James (301)123-3459
Arthur Paul (202)865-9090
Todd Shurn (410)560-8909
Richard Okpala 202 388 410
what my current program is outputting the phonenumber if firstname and lastname is present in file but if its nothow do i output phone number isnt here my current code.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void lookup_name(ifstream&, string&, string&, string&); // prototype
int main()
{
ifstream myfile;
string name, lastname, phonenumber;
char choice;
do
{
myfile.open("infile.txt");
cout << "What is the First name? " << endl;
cin >> name;
cout << "what is your last name?" << endl;
cin >> lastname;
lookup_name(myfile, name, lastname, phonenumber);
cout << "Do you want to lookup another name<Y/N" << endl;
cin >> choice;
} while (choice == 'Y');
return 0;
}
void lookup_name(ifstream& myfile, string& name, string& lastname, string& phonenumber)
{
string name1, name2, fullname, secondname, dummy;
for (int i = 0; i < 5; i++) {
myfile >> name1 >> name2;
fullname = name1 + name2;
secondname = name + lastname;
if (fullname == secondname) {
myfile >> phonenumber;
cout << phonenumber << endl;
myfile.close();
break;
}
else if (fullname != secondname) {
myfile >> dummy;
phonenumber = dummy;
}
Just return whether you found it or not from your lookup function
int lookup_name(ifstream& myfile, string& name, string& lastname, string& phonenumber)
{
string name1, name2, fullname, secondname, dummy;
for (int i = 0; i < 5; i++) {
myfile >> name1 >> name2;
fullname = name1 + name2;
secondname = name + lastname;
if (fullname == secondname) {
myfile >> phonenumber;
cout << phonenumber << endl;
myfile.close();
return 1;
}
else if (fullname != secondname) {
myfile >> dummy;
phonenumber = dummy;
}
}
return 0;
}
Then use the return value
if ( ! lookup_name(myfile, name, lastname, phonenumber) ) {
cout << "Nope, didn't find it!" << endl;
}
Related
Hey so I have this text file:
1:Vegetarian Dishes:Lettuce:1.99
2:Vegetarian Dishes:Tomato:0.99
3:Drinks:Water:0.5
4:Meat Dishes:Burger:4.99
5:Fish Dishes:Fishes:5
6:Drinks:Coka cola:2.5
7:Drinks:Fanta:1.2
8:Drinks:Absolut:12.99
9:Drinks:Wiskey:9.99
10:Vegetarian Dishes:Lemon:0.99
11:Vegetarian Dishes:Green:2.99
12:Meat Dishes:Pizza:4.99
13:Fish Dishes:Fishes2:5.99
14:Drinks:Milk shake:4.99
15:Vegetarian Dishes:Vegan Sandwich:3.99
and i have objects of Dish class, so I want to read the file and add each dish to a Dish object.
Then i have an array of Dishes. Its supposed to store _itemNo:category:description:price.
Below is my code.
The problem is that it doesn't read the file correctly. Do you see any problems?
Code:
Dish::Dish() { }
Dish::Dish(int itemNo, string category, string description,
double price): _itemNo(itemNo), _category(category),
_description(description), _price(price) { }
void Dish::displayDish(void){
cout << setw(15) << left << _itemNo << setw(30) << left << _category
<< setw(45) << left << _description << _price << endl;
}
DishDb::DishDb(): _nElems(0) { }
void DishDb::addDish(int itemNo, string category, string description,
double price){
_menu[_nElems] = Dish(itemNo, category, description, price);
_nElems++;
}
void DishDb::display(){
int i;
cout <<setw(40) << "MENU" << endl << endl;
cout << "Item No" << setw(15) << "Category" << setw(30)
<< "Description" << setw(40)<< "Price" << endl << endl;
for(i = 0; i < _nElems; i++){
_menu[i].displayDish();
}
}
int main(){
/*Select file name for the bills to be stored in*/
string transFilename;
cout << "Enter today's transaction file name: ";
cin >> transFilename;
/*Load the menu*/
/*Adding each dish object into the _nenu array*/
/*Couldn't make this part object oriented*/
DishDb ddb;
string fileName;
int itemNo;
double price;
string description;
string category;
int i;
int numOfDishes = 0;
cout << "Enter file name: ";
cin >> fileName;
ifstream inFile(fileName);
while(i<15){
inFile >> itemNo;
getline(inFile, category, ':');
getline(inFile, description, ':');
inFile >> price;
numOfDishes++;
Dish(itemNo, category, description, price);
ddb.addDish(itemNo, category, description, price);
i++;
}
ddb.display();
inFile.close();
/* while(inFile >> itemNo && getline(inFile, category, ':') &&
getline(inFile, description, ':') && inFile >> price){
numOfDishes++;
Dish(itemNo, category, description, price);
ddb.addDish(itemNo, category, description, price);
}
*/
cout << endl << "Menu was loaded.";
return 0;
}
I've tried 2 ways of reading the file. With the first i was just checking if the file was beging read correctly but its not.
The following code should work for you:
int main() {
std::ifstream file("dishes.txt");
std::string temp, snum, category, description, sprice;
while (std::getline(file, snum, ':') &&
std::getline(file, category, ':') &&
std::getline(file, description, ':') &&
std::getline(file, sprice)) {
// Do whatever you want with:
// * snum (must convert to integer)
// * category
// * description
// * sprice (must convert to float)
}
}
I am working on this problem for a college course and I'm unsure why it isn't working. I thought I had everything setup correctly, but when I try running the program the file won't open on the first attempt at inputting the file name and when I input it again I get an "Exception Thrown" error in the "xmemory" part that I have no idea what any of it means.
The input file that the program is taking data from is just a text file with the following data:
201742 Sponge Bob 82.6
201701 Patrick Star 14.1
201753 Squidward Tentacles 85.43
201744 Sandy Squirrel 75.61
201700 Plankton Plank 100.0
The final output of the program should display the highest and lowest grade with the students first and last name, the average score, and the number of students tested. Any help would be much appreciated.
// Zane Richards
// Lab 10 Q2
// 4/6/2020
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
#include <fstream>
using namespace std;
struct student {
int ID;
string firstName;
string lastName;
float grade;
};
void maxGradeFunc(struct student* s, int size)
{
float maxGrade = 0;
string firstName, lastName;
for (int i = 0; i < size; ++i)
{
if (s[i].grade > maxGrade)
{
maxGrade = s[i].grade;
firstName = s[i].firstName;
lastName = s[i].lastName;
}
}
cout << "Maximum grade is " << maxGrade << endl;
cout << "The name of the student with the grade is: " << firstName << " " << lastName << endl;
}
void minGradeFunc(struct student* s, int size)
{
float minGrade = 999;
string firstName, lastName;
for (int i = 0; i < size; ++i)
{
if (s[i].grade < minGrade)
{
minGrade = s[i].grade;
firstName = s[i].firstName;
lastName = s[i].lastName;
}
}
cout << "Maximum grade is " << minGrade << endl;
cout << "The name of the student with the grade is: " << firstName << " " << lastName << endl;
}
void avgGradeFunc(struct student* s, int size)
{
float sum = 0;
for (int i = 0; i < size; ++i)
{
sum += s[i].grade;
}
float avg = sum / size;
cout << "Avearge grade is " << avg << endl;
cout << "The total number of students are: " << sum << " students" << endl;
}
int main()
{
ifstream inFile;
string fileName = "";
struct student s[5];
int ID;
string firstName, lastName;
float grade;
int i = 0;
cout << "Please enter the input file name: "; //File is named "Student.txt"
cin >> fileName;
while (!inFile.is_open()) {
cout << "Sorry, the file did not open. \nTry again, or type \"cancel\" to quit: ";
cin >> fileName;
if (fileName == "cancel") {
cout << "Cancelling..." << endl;
break;
}
else {
inFile.open(fileName);
}
}
while (inFile.is_open()) {
inFile >> ID;
s[i].ID = ID;
inFile >> firstName;
s[i].firstName = firstName;
inFile >> lastName;
s[i].lastName = lastName;
inFile >> grade;
s[i].grade = grade;
i++;
}
maxGradeFunc(s, 5);
minGradeFunc(s, 5);
avgGradeFunc(s, 5);
return 0;
}
Here is the error code I'm getting: https://i.stack.imgur.com/i35Oq.png
Figured out the issue, deleted the code that allowed for multiple attempts, and changed it to just open the file and that fixed it. Thanks for the help everyone, much appreciated!
So, I've been having an issue where my program is trying to read a file, "LineUp.txt", and I organized the file to have the names alphabetical, but it won't read more than one name, it just reads the first name over and over. I'm using a for loop, not a while loop, which I haven't seen before in other problems. I appreciate the help! Here is the code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main (){
ifstream myFile;
string name, front, back;
int numOfStudents, i;
myFile.open("LineUp.txt");
if(!myFile)
cout << "File not found";
cout << "Please enter the number of students: ";
cin >> numOfStudents;
myFile >> name;
front = name;
back = name;
while(myFile >> name){
if(name < front)
front = name;
if(name > back)
back = name;
}
for(i = 0; i < numOfStudents; i++){
myFile >> name;
cout << name << endl;
}
return 0;
}
The while loop would exhaust your input stream.
If you want to read from the file again you would have to create a new input stream.
myFile.open("LineUp.txt");
if(!myFile)
cout << "File not found";
cout << "Please enter the number of students: ";
cin >> numOfStudents;
myFile >> name;
front = name;
back = name;
while(myFile >> name){
if(name < front)
front = name;
if(name > back)
back = name;
}
ifstream myFile2("LineUp.txt"); //Create a new stream
for(i = 0; i < numOfStudents; i++){
myFile2 >> name;
cout << name << endl;
}
I am creating a directory program that prompts a user for a file name and reads the file into a string array. I'm have trouble in my SearchFirstName function. I get an error:'std::string' has no member named 'userRecord'. I'm not sure how to fix this because userRecord is declared.
Header
#include<string>
using namespace std;
enum Title {Mr, Mrs, Ms, Dr, NA};
struct NameType {
Title title;
string firstName;
string lastName;
};
struct AddressType {
string street;
string city;
string state;
string zip;
};
struct PhoneType {
int areaCode;
int prefix;
int number;
};
struct entryType {
NameType name;
AddressType address;
PhoneType phone;
};
const int MAX_RECORDS = 50;
Code
// string bookArray[MAX_RECORDS];
entryType bookArray[MAX_RECORDS]; //Solution
int bookCount = 0;
void OpenFile(string& filename, ifstream& inData)
{
do {
cout << "Enter file name to open: ";
cin >> filename;
inData.open(filename.c_str());
if (!inData)
cout << "File not found!" << endl;
} while (!inData);
if(inData.is_open())
{
for(int i=0; i<MAX_RECORDS;i++)
{
inData>> bookArray[bookCount];
++bookCount;
}
}
}
void SearchFirstName(ifstream& inData)
{
entryType userRecord; // Declaration of userRecord
string searchName;
string normalSearchName, normalFirstName;
char choice;
bool found = false;
cout << "Enter first name to search for: ";
cin >> searchName;
for(int i = 0; i < bookCount; ++i){
normalFirstName = NormalizeString(bookArray[i].userRecord.name.firstName);
// Convert retrieved string to all uppercase
if (normalFirstName == normalSearchName) { // Requested name matches
PrintRecord(bookArray[i].userRecord.name.firstName);
cout << "Is this the correct entry? (Y/N)";
cin >> choice;
choice = toupper(choice);
cout << endl;
if (choice == 'Y') {
found = true;
break;
}
}
}
// Matching name was found before the end of the file
if (inData && !found){
cout << "Record found: " << endl;
PrintRecord(userRecord);
cout << endl;
}
else if (!found) // End of file. Name not found.
{
cout << searchName << " not found!" << endl << endl;
}
// Clear file fail state and return to beginning
inData.clear();
inData.seekg(0);
}
string bookArray[MAX_RECORDS];
bookArray is of type string.It should be
entryType bookArray[MAX_RECORDS];
Also
normalFirstName = NormalizeString(bookArray[i].userRecord.name.firstName);
bookArray[i] cannot have userRecord as a member.userRecord is variable that you have declared.
It should be
normalFirstName = NormalizeString(bookArray[i].name.firstName);
I'm creating an address book program that allow user to search by first name, last name,phone number and address. The user is prompted to enter a file name and the file is read into an array. I'm having trouble modifying by existing SearchFirstName function to loop through array. I have read over this topic multiple times I'm just not understanding it. Any help would be greatly appreciated.
File
Susan, Smith, 123 456 789
101 Main Street
Bob, Smith, 567 345 9076
456 Market Street
Header File
#include<string>
using namespace std;
enum Title {Mr, Mrs, Ms, Dr, NA};
struct NameType {
Title title;
string firstName;
string lastName;
};
struct AddressType {
string street;
string city;
string state;
string zip;
};
struct PhoneType {
int areaCode;
int prefix;
int number;
};
struct entryType {
NameType name;
AddressType address;
PhoneType phone;
};
const int MAX_RECORDS = 50;
struct addressBookType {
entryType record[MAX_RECORDS];
int numEntries;
};
Code
string bookArray[MAX_RECORDS];
int main()
{
entryType userRecord;
string filename;
ifstream inData;
char searchOption;
OpenFile(filename, inData);
MainMenu(inData, filename);
return 0;
}
void OpenFile(string& filename, ifstream& inData)
{
do {
cout << "Enter file name to open: ";
cin >> filename;
inData.open(filename.c_str());
if (!inData)
cout << "File not found!" << endl;
} while (!inData);
if(inData.is_open())
{
for(int i=0; i<MAX_RECORDS;i++)
{
inData>> bookArray[i];
}
}
}
// Searches passed file stream for a first name read from the user
void SearchFirstName(ifstream& inData)
{
string searchName;
entryType userRecord;
string normalSearchName, normalFirstName;
char choice;
bool found = false;
cout << "Enter first name to search for: ";
cin >> searchName;
normalSearchName = NormalizeString(searchName); // Convert name to all uppercase
// Loop through all records in the file
while (GetRecord(inData, userRecord)){
normalFirstName = NormalizeString(userRecord.name.firstName); // Convert retrieved string to all uppercase
if (normalFirstName == normalSearchName) { // Requested name matches
PrintRecord(userRecord);
cout << "Is this the correct entry? (Y/N)";
cin >> choice;
choice = toupper(choice);
cout << endl;
if (choice == 'Y') {
found = true;
break;
}
}
}
// Matching name was found before the end of the file
if (inData && !found){
cout << "Record found: " << endl;
PrintRecord(userRecord);
cout << endl;
}
else if (!found) // End of file. Name not found.
{
cout << searchName << " not found!" << endl << endl;
}
// Clear file fail state and return to beginning
inData.clear();
inData.seekg(0);
}
My attempt
void SearchFirstName(ifstream& inData)
{
string searchName;
entryType userRecord;
cout << "Enter first name to search for: ";
cin >> searchName;
string newSearchName = NormalizeString(searchName);
string upFirst = NormalizeString(userRecord.name.firstName);
for (int i=0;i<MAX_RECORDS;i++)
{
while(newSearchName == upFirst)
{
if (bookArray[i]== upFirst)
{
cout<<"Name Found";
cout <<bookArray[i]; //test case
}
}
}
}
Create your array, in this case it'll be an std::vector because that is more simple to use, by running your GetRecord function inside of a while loop and appending the result to the vector w/vector_variable_name.push_back(NormalizeString(value_returned_from_GetRecord));. The NormalizeString part is so you don't have to call it billions of times later.
Pass in your array like so void SearchFirstName(std::vector<entryType> *in_data_arr>)
Change your while loop to a for loop: for (int i = 0; i < in_data_arr.size(); i++) {
Inside the loop change normalSearchName = NormalizeString(searchName); to normalSearchName = in_data_arr[i].name.firstName;
And from there it should generally be identical.