How to fix this code - c++

Please, how to fix this code
[Error] a function-definition is not allowed here before '}' token
[Error] expected '}' at the end of input
I don't know what's the problem with my code even though I've already checked the compiler errors
#include<iostream>
using namespace std;
struct name_type
{
string first,middle,last;
};
struct SD
{
name_type name;
float grade;
};
const int MAX_SIZE = 35;
int isFull(int last) {
if(last == MAX_SIZE - 1) {
return(1);
}
else {
return(0);
}
}
int isEmpty(int last) {
if(last < 0) {
return(1);
}
else {
return(0);
}
}
main()
{
SD SD2[MAX_SIZE];
int last = -1;
if(isEmpty(last))
{
cout << "List is empty\n";
}
for (int a=0; a <35; a++)
{
cout << "Enter first name:.....";
cin >> SD2[a].name.first;
cout << "Enter middle name:....";
cin >> SD2[a].name.middle;
cout << "Enter last name:......";
cin >> SD2[a].name.last;
cout << "Enter your grade:.....";
cin >> SD2[a].grade;
cout << '\n';
}
system("cls");
cout << "1 - Add";
cout << "2 - Delete";
cout << "3 - Search";
cout << "4 - Print";
cout << "5 - Exit";
string lname, fname;
int choice, search;
cin >> choice;
if(choice == 3) {
cin >> fname;
cin >> lname;
int index = search;
(SD2, lname, fname, last);
if (index > 0) {
cout << "ERROR\n";
}
else {
cout << "The grade of " << lname << "," << fname << "is " << SD2[index].grade;
}
}
int search(SD list [], string search_lname, string search_fname, int last) {
int index;
if(isEmpty(last)==1) {
cout << "\nThe list is Empty!";
}
else {
index = 0;
while(index!= last+1 && list[index].name.first != search_fname && list[index].name.last != search_lname) {
++index;
}
if(index != last + 1) {
cout << "\nItem Requested is Item" << index + 1 << ".";
return index;
}
else {
cout << "\n Item Does Not Exist.";
}
}
return -1; // list is empty or search item does not exist
}
}

One of the problems is in your declaration of the main function:
main()
In c++, the main() function must have a return type of int. Sin you have not specified any data type for the return value of main(), it sets the return data type to void, which is produces the error just before main(). To learn and understand more about main() for C++, visit the following link Main Function.
To sort this, change the above line of code to:
int main() // notice that the return type here is int. This is required in c++
Another thing: in these lines:
int index = search;
(SD2, lname, fname, last);
Over here, you want to pass SD2, lname, fname and last to the search() function. However, your syntax is wrong. The function and its parameters when called cannot be split by a semicolon, because a semicolon terminates the statement. Therefore, the compiler sees search as a variable, not a function. This along with the statement following it cause the error. You should change those 2 lines to:
int index = search(SD2, lname, fname, last); // this is proper syntax to call a function.
Also, you need to take out search() from inside the main() function and place it above the main() function. That is also causing an error.

Related

Dealing with file io in c++

I have a program that takes input for names and outputs the last names in a string. The task I have now is to include FileIO in it. Specifically, "get user input for the filename, and then read the names from the file and form the last name string."
When I run the program, the console will show the name string from the text file. But only initially. As you keep entering names, that string disappears. Also, my user input for file name seems to be doing nothing, because I can enter anything and it still show the string of last names from the text file.
Here is what I have so far. Included all of it, just to make sure.
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
using namespace std;
// function declerations
int Menu();
void getName(vector<string> &names, int &count);
void displayName(vector<string> &names, int count);
string getLastNames(vector<string> &names, int count);
int main()
{
vector<string> names;
int count = 0;
int choice = Menu();
ifstream File;
string line;
cout << "Enter file name: ";
getline(cin,line);
File.open("File.txt");
while(File.good()){
getline(File,line);
cout << line << endl;
}
File.close();
while (choice != 0)
{
// switch statement to call functions based on users input
switch (choice)
{
case 1: {
getName(names, count);
} break;
case 2: { displayName(names, count); } break;
case 3: {
cout << getLastNames(names, count) << endl;
} break;
case 0: {
return 0;
} break;
}
choice = Menu();
}
return 0;
}
// function definition for vector of strings
void getName(vector<string> &names, int &count)
{
string name;
// get input for name
cout << "Enter name: ";
getline(cin, name);
// find position of space in string
int pos = name.find(' ');
// reverse order of name
if(pos != -1) {
string first = name.substr(0, pos);
string last = name.substr(pos+1);
name = last + "," + first;
}
// add name to end of vector
names.push_back(name);
count++;
}
// give user option of what to do
int Menu() {
int choice;
cout << "1. Add a name" << endl;
cout << "2. Display names " << endl;
cout << "3. Show all Last Names" << endl;
cout << "0. Quit" << endl;
cout << "Enter a option: ";
cin >> choice;
// if outside of above choices, print 'choice not on list'
while (choice < 0 || choice > 3)
{
cout << "Choice not on list: ";
cin >> choice;
}
cin.ignore();
return choice;
}
// defining function that gets last names
string getLastNames(vector<string> &names, int count) {
stringstream ss;
for (int i = 0; i<count; i++)
{
int pos = names[i].find(',');
if (pos != -1) {
ss << "\"" << names[i].substr(0, pos) << "\", ";
} else {
ss << "\"" << names[i] << "\", ";
}
}
return ss.str();
}
// display the names
void displayName(vector<string> &names, int count)
{
if (count == 0)
{
cout << "No names to display" << endl;
return;
}
for (int i = 0; i<count; i++)
{
cout << names[i] << endl;
}
}

Reading a file from user input c++

I have been trying to get this to work for an hour now and I know it can't be that difficult a fix. Every time I enter the file.txt name it comes up as invalid file. I tried moving the files to the same directory as the .cpp file and everything but I just cant get it to read. Help would be appreciated.
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<assert.h>
using namespace std;
const int SIZE = 20;
void readIntFile(ifstream& x, int intArray[], int size, int &length);
void printValues(int intArray[], int& length);
char getSentinel();
int main()
{
ifstream inputStream;
const int size = SIZE;
string fileName;
int length = 0;
bool isEmpty = false;
int intArray[size];
char sentinel = 'y';
while (sentinel == 'y' || sentinel == 'Y')
{
cout << "Please enter the name of the file: ";
cin >> fileName;
inputStream.open(fileName);
if (inputStream.bad() || inputStream.fail())
{
cout << "Error, <" << fileName << "> is Invalid File Name.";
}
if (fileName.empty())
{
isEmpty = true;
}
if (isEmpty == true)
{
cout << "Error <" << fileName << "> has no data.";
}
if (inputStream.good() && isEmpty == false)
{
readIntFile(inputStream, intArray, size, length);
printValues(intArray, length);
inputStream.close();
}
sentinel = getSentinel();
}
return 0;
}
void readIntFile(ifstream& x, int intArray[], int size, int& length)
{
int count = 0;
int arrayLocation = -1;
int fileInputValue = 0;
x >> fileInputValue;
while (!x.eof())
{
count ++;
if (count > SIZE)
{
cout << "The file has more than <" << SIZE << "> values." << endl;
break;
}
else
{
arrayLocation ++;
intArray[count] = fileInputValue;
x >> fileInputValue;
}
}
}
void printValues(int intArray[], int& length)
{
assert(length > 0);
cout << "<" << length << "> values processed from the file. The values are: ";
for (int i=0; i <= length; i++)
{
cout << intArray[i] << ", ";
}
}
char getSentinel()
{
char userInput = 'n';
bool inputCheck = false;
cout << "Do you wish to process another file (y/n)?" << endl;
cin >> userInput;
do
{
if (userInput == 'y' || userInput == 'Y' || userInput == 'n' || userInput == 'N')
{
inputCheck = true;
}
else
{
cout << "Invalid response: <" << userInput << ">" << endl;
cout << "Do you wish to process another file (y/n)?" << endl;
cin >> userInput;
}
} while (!inputCheck);
return userInput;
}
Your basic problem is in function
void readIntFile(ifstream& x, int intArray[], int size, int& length)
You do not set the output variable length. And you use the wrong index value for your array. Please check.
Additionally there are many other problems in your code.
I will now paste your code, amended with my comments comments, where problems are or where things should be improved.
Please see:
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<assert.h>
using namespace std; // Should never be used. Always use fully qualified names
const int SIZE = 20; // Please use constexpr
// Do not use C-Style function prototypes. Put main at the bottom
// Do not use C-Style Arrays
// In C++ (C-Style-)Arrays are different. You actually do not pass an array to your function
// but a decyed pointer. You can pass an array by pointer or by reference, but this has a different syntax
void readIntFile(ifstream& x, int intArray[], int size, int &length);
void printValues(int intArray[], int& length);
char getSentinel();
int main()
{
// All variables shall be initialized at the point of defintion
ifstream inputStream; // You should define variables just before you need then
const int size = SIZE; // This is code duplication. And constexpr should be used
string fileName;
int length = 0;
bool isEmpty = false;
int intArray[size]; // C-Style Arrays should not be used. Use std::array or best, std::vector
char sentinel = 'y'; // You could use universal initializer syntax with braced initializer
while (sentinel == 'y' || sentinel == 'Y')
{
cout << "Please enter the name of the file: ";
cin >> fileName;
inputStream.open(fileName); // The constructor can open the file for you
if (inputStream.bad() || inputStream.fail()) // This is too complicated
{
cout << "Error, <" << fileName << "> is Invalid File Name.";
}
if (fileName.empty()) // Check is too late and not necessary
{
isEmpty = true;
}
if (isEmpty == true)
{
cout << "Error <" << fileName << "> has no data.";
}
if (inputStream.good() && isEmpty == false)
{
readIntFile(inputStream, intArray, size, length);
printValues(intArray, length);
inputStream.close(); // Destructor will clsoe the file for you
}
sentinel = getSentinel();
}
return 0;
}
// Not optimal function prototype
void readIntFile(ifstream& x, int intArray[], int size, int& length)
{
// the whole design / logic is very strange
int count = 0;
int arrayLocation = -1; // More then strange. Shows that this is a bad design
int fileInputValue = 0;
x >> fileInputValue;
while (!x.eof()) // Bad or even wrong design
{
count ++; // Wrong. See below. array will be filled with starting with index one
if (count > SIZE)
{
cout << "The file has more than <" << SIZE << "> values." << endl;
break;
}
else
{
arrayLocation ++; // This variable is not used
intArray[count] = fileInputValue;
x >> fileInputValue;
}
}
// Nobody will set the length variable
}
void printValues(int intArray[], int& length)
{
assert(length > 0); // Basically OK, but no necessary here. Cannoz happen
cout << "<" << length << "> values processed from the file. The values are: ";
for (int i=0; i <= length; i++)
{
cout << intArray[i] << ", ";
}
// There is now newline character used anywhere
}
// Very complicated
char getSentinel()
{
char userInput = 'n';
bool inputCheck = false;
cout << "Do you wish to process another file (y/n)?" << endl;
cin >> userInput;
do
{
if (userInput == 'y' || userInput == 'Y' || userInput == 'n' || userInput == 'N')
{
inputCheck = true;
}
else
{
cout << "Invalid response: <" << userInput << ">" << endl;
cout << "Do you wish to process another file (y/n)?" << endl;
cin >> userInput;
}
} while (!inputCheck);
return userInput;
}
Next, I will make your code working, by fixing the biggest problems. I will still follow your programming style.
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<assert.h>
constexpr int MaxArraySize = 20;
using IntArray = int[MaxArraySize];
void readIntFile(std::ifstream& x, int intArray[], int& length)
{
length = 0;
int value{};
while (x >> value)
{
if (length >= MaxArraySize)
{
std::cout << "The file has more than <" << MaxArraySize << "> values.\n";
break;
}
else
{
intArray[length++] = value;
}
}
}
void printValues(int intArray[], int& length)
{
std::cout << "\n<" << length << "> values processed from the file. The values are: ";
for (int i=0; i < length; i++)
{
std::cout << intArray[i] << ", ";
}
std::cout << "\n\n";
}
bool getSentinel()
{
char userInput{'n'};
bool valid = false;
while (not valid)
{
std::cout << "\n\nDo you wish to process another file (y/n)?\n";
std::cin >> userInput;
if (userInput != 'y' && userInput != 'Y' && userInput != 'n' && userInput != 'N')
{
std::cout << "Invalid response: <" << userInput << ">\n\n";
}
else {
valid = true;
}
}
return ( userInput=='y' || userInput=='Y');
}
int main()
{
int intArray[MaxArraySize];
bool sentinel = true;
while (sentinel)
{
std::cout << "Please enter the name of the file: ";
std::string fileName{};
std::cin >> fileName;
if (fileName.empty())
{
std::cout << "Error <" << fileName << "> has no data.\n\n";
}
else {
std::ifstream inputStream(fileName);
if (!inputStream)
{
std::cout << "Error, <" << fileName << "> is Invalid File Name.\n\n";
}
else
{
int length = 0;
readIntFile(inputStream, intArray, length);
printValues(intArray, length);
}
}
sentinel = getSentinel();
}
return 0;
}
and, in the end, because we are in a C++ site here, I will show (one of many possible) a more advanced C++ solution.
This is just for information and to grab some ideas for the future
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<vector>
#include<algorithm>
#include<iterator>
#include<initializer_list>
// Some aliases for easier reading and saving typing work
using DataType = int;
using Vector = std::vector<DataType>;
// Define an "in" operator
struct in {
in(const std::initializer_list<char>& il) : ref(il) {}
const std::initializer_list<char>& ref;
};
bool operator,(const char& lhs, const in& rhs) {
return std::find(rhs.ref.begin(), rhs.ref.end(), lhs) != rhs.ref.end();
}
int main() {
// As long as the user wants to read files
for (bool userWantsToContinue{true}; userWantsToContinue;) {
std::cout << "\nPlease enter a valid filename: ";
if (std::string filename{}; std::cin >> filename) {
// Open the file for reading and check, it it is open
if (std::ifstream inputStream{filename}; inputStream) {
// Read all data from the file
Vector data(std::istream_iterator<DataType>(inputStream), {});
// Now show result to user
std::cout << "\nRead values are:\n";
std::copy(data.begin(), data.end(), std::ostream_iterator<DataType>(std::cout, " "));
}
else std::cerr << "\nError: Could not open file '" << filename << "' for reading\n\n";
}
else std::cerr << "\nError: Problem with filename input\n\n";
// Ask, if the user wants to continue
bool validInput{false};
while (not validInput) {
std::cout << "\n\nDo you want to read more files? Please enter 'y' or 'n' ";
if (char selection{}; (std::cin >> selection) && (selection, in{'y','Y','n','N',}) ) {
validInput = true;
userWantsToContinue = (selection, in{'y','Y'});
}
else {
std::cout << "\n\nInvalid input, please retry\n\n";
}
}
}
return 0;
}
Try using an full absolute filename, not a relative one.
And replace cin >> fileName; with std::getline(std::cin, fileName); Otherwise, it will easily break. The getline version is much more robust.
If this was not enough, read the answer of: How do I get the directory that a program is running from? and do the checks suited for your system to find out your "working directory". This is the place where you input file must be, if you don't use absolute paths.

vector pointers and retrieving data

I'm a beginner at coding in C++ and every other language. The problem I'm having here is in main() with the first (else if) where (UserInput == sell). I would like the function to print the data stored in the object #listPos to retrieve the cost and input it into my incomplete Profit() function, but every time I dereference the pointer (Search) I get an error code. There's something I'm missing big time please help!!
Ive already tried (*search) but there's a huge error code.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class UnSold{
public:
UnSold(string NameOfShoe, int PurchasePrice ){
name = NameOfShoe;
cost = PurchasePrice;
return;
}
void SetName(string NameOfShoe){
name = NameOfShoe;
return;
}
void SetCost(int PurchasePrice){
cost = PurchasePrice;
return;
}
string GetName() const {
return name;
}
int GetCost() const{
return cost;
}
void Profit();
void PrintItem();
private:
string name;
int cost;
};
void UnSold::Profit(){
static int profit = 0;
//profit += (sold-cost);
}
void UnSold::PrintItem(){
cout << "Name: " << this->name << " Cost: " << this->cost << endl;
}
void PrintEverything(vector<UnSold*> AllItems) {
unsigned int i;
for (i=0; i<AllItems.size(); ++i) {
cout<< i+1 << " ";
(*AllItems.at(i)).PrintItem();
}
}
int main(){
vector<UnSold*> Inventory;
string Name;
int Cost;
string UserInput;
unsigned int listPos;
UnSold* newItem = nullptr;
UnSold* search = nullptr;
while ( UserInput != "quit") {
cout << "Do you want to add, sell, print or quit?" <<endl;
cin >> UserInput;
if ( UserInput == "add") {
cout << "Enter item name: "<<endl;
cin >> Name;
cout << "Enter item cost: " << endl;
cin >> Cost;
newItem = new UnSold(Name, Cost);
Inventory.push_back(newItem);
}
else if ( UserInput == "sell") {
cout << "List Positon: ";
cin >> listPos;
if ( listPos < Inventory.size()){
cout << " Item Sold and Removed from list position " << listPos <<endl;
search = Inventory.at(listPos-1);
//cout<< "contents of Search: "<< search << endl;
delete search;
Inventory.erase(Inventory.begin() + (listPos -1));
}
else{
cout << "Error"<<endl;
}
}
else if ( UserInput == "print") {
PrintEverything(Inventory);
}
else if ( UserInput != "quit"){
}
}
return 0;
}
This is a compile error.
Remove line 85: newItem.at(listPos - 1); and it runs just fine in visual studio.
The issue is that newItem is a pointer to an element. I assume you meant to use Inventory here instead. However, that logic was already done on the previous line.
On a side note, I stongly advise against storing owning pointers like this. There's no good reason in this case not to just use vector<UnSold> instead.
else if ( UserInput == "sell") {
cout << "List Positon: ";
cin >> listPos;
if ( listPos < Inventory.size()){
cout << " Item Sold and Removed from list position " << listPos <<endl;
search = Inventory.at(listPos-1);
//cout<< "contents of Search: "<< search << endl;
delete search;
Inventory.erase(Inventory.begin() + (listPos -1));
Here you mix the use of listPos and listPos - 1.
If you're allowing the user to input position 0 indexed, then
Inventory.at(listPos-1) should be Inventory.at(listPos) and
Inventory.erase(Inventory.begin() + (listPos -1)) should be Inventory.erase(Inventory.begin() + (listPos)).
If you're letting them input the position with the indexing starting at 1, then
if (listPos < Inventory.size()) should be
if(listPos <= Inventory.size() && listPos > 0)

What is a deleted function, and why only my functions that I pass files into are considered deleted? [duplicate]

This question already has answers here:
Using fstream Object as a Function Parameter
(3 answers)
Closed 6 years ago.
#include <bits/stdc++.h>
using namespace std;
class contact {
private:
vector< pair<string, int> > contact_info;
public:
void add_contact(string contact_name, int contact_number) {
contact_info.push_back(make_pair(contact_name, contact_number));
sort(contact_info.begin(),contact_info.end());
}
void edit_contact(string contact_name) {
int found_at;
for (unsigned int i =0; i < contact_info.size(); i++) {
if (contact_info[i].first == contact_name) {
found_at = i;
}
}
if (contact_info[found_at +1].first == contact_name) {
int choice;
int counter = found_at;
int index = 1;
while (contact_info[counter].first == contact_name) {
cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
counter++;
index++;
}
cout << "Choose any please: ";
cin >> choice;
found_at = found_at - (choice - 1);
}
cout << "Enter the new number: ";
cin >> contact_info[found_at].second;
}
void show_all() {
for (unsigned int i =0; i < contact_info.size(); i++) {
cout << contact_info[i].first << " " << contact_info[i].second << endl;
}
}
void delete_contact(string contact_name) {
int found_at;
for (unsigned int i =0; i < contact_info.size(); i++) {
if (contact_info[i].first == contact_name) {
found_at = i;
}
}
if (contact_info[found_at +1].first == contact_name) {
int choice;
int counter = found_at;
int index = 1;
while (contact_info[counter].first == contact_name) {
cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
counter++;
index++;
}
cout << "Choose any please: ";
cin >> choice;
found_at = found_at - (choice - 1);
}
contact_info.erase(contact_info.begin()+found_at);
}
void writeFile(ofstream contact_file) {
for (unsigned int i =0; i < contact_info.size(); i++) {
contact_file << contact_info[i].first << " " << contact_info[i].second << endl;
}
}
void readFile(ifstream contact_file) {
string input;
while (!contact_file.eof()) {
contact_file >> input;
size_t pos = input.find(" ");
string name = input.substr(0,pos);
string number_str = input.substr(pos);
int number = stoi(number_str) ;
contact_info.push_back(make_pair(name,number));
}
}
};
int main()
{
int choice;
ifstream contacts_file_read;
contacts_file_read.open("contacts.txt");
ofstream contacts_file_write;
contacts_file_write.open("contacts.txt");
bool in_prog = true;
contact contacts;
string name;
int number;
while (in_prog) {
cout << "1. Add contacts" << endl
<< "2. Edit contact" << endl
<< "3. Delete contact" << endl
<< "4. Show all" << endl
<< "5. exit" << endl;
cout << "Your choice: ";
cin >> choice;
contacts.readFile(contacts_file_read);
if (choice == 1) {
cout << "Enter name & number separated by a space: ";
cin >> name >> number;
contacts.add_contact(name, number);
} else if (choice == 2) {
cout << "Enter name of contacts to be edited: ";
cin >> name;
contacts.edit_contact(name);
} else if (choice == 3) {
cout << "Enter name of contact to be deleted: ";
cin >> name;
contacts.delete_contact(name);
} else if (choice == 4) {
contacts.show_all();
} else if(choice == 5) {
contacts.writeFile(contacts_file_write);
} else {
cout << "Wrong choice" << endl;
}
}
return 0;
}
So, I was asked in my programming class to make a phone book application in C++ using only objects, so this is my attempt at it.
All functions are good, I did recompile the program after finishing each function at it gave me 0 errors, however whenever I try to call writeFile or readFile function that were previously working fine, now the compiler gave me an error of "error: use of deleted functions... "
I don't know what are deleted functions and why only functions that take file objects as an argument are treated as such.
Can anyone please help?
Thanks.
Objects of type std::ifstream are not copyable -- indeed, the object represents the unique handle of an open file, and it would be difficult to conceptualize what it would mean to copy such unique responsibility.
Indeed, this inability to copy an object is encoded by making the copy constructor deleted, which causes the error that you see when you do attempt to copy it.
Your code should pass the original ifstream, not a copy (by taking a reference parameter):
void readFile(ifstream & contact_file)
// ^^^^^^^^^^

Extra string outputs if user input is more than one word

This is my first time asking a question on here, so be gentle lol. I wrote up some code for an assignment designed to take information from a (library.txt datatbase) file, store it in arrays, then access/search those arrays by title/author then output that information for the user based on what the user enters.
The issue I am having is, whenever the user enters in a search term longer than one word, the output of "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: " is repeated several times before closing.
I am just looking to make this worthy of my professor lol. Please help me.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
struct Book
{
string title;
string author;
};
int loadData(string pathname);
char switchoutput();
void showAll(int count);
int showBooksByAuthor(int count, string name);
int showBooksByTitle(int count, string title);
int FindAuthor(int count, string userinput);
int FindTitle(int count, string userinput);
void ConvertStringToLowerCase(const string orig, string& lwr); //I found this program useful to convert any given string to lowercase, regardless of user input
const int ARRAY_SIZE = 1000;
Book books[ARRAY_SIZE];
int main()
{
string pathname;
string name;
string booktitle;
int count = 0;
int counta = 0;
int countt = 0;
char input = 0;
cout << "Welcome to Jacob's Library Database." << endl;
cout << "Please enter the name of the backup file: " ;
cin >> pathname;
count = loadData(pathname);
cout << count << " records found in the database." << endl;
while (toupper(input != 'Q'))
{
input = switchoutput(); // function call for switchoutput function
switch (input)
{
case 'A':
cout << "Author's Name: ";
cin >> name;
counta = showBooksByAuthor(count, name);
cout << counta << " records found." << endl;
break;
case 'T':
cout << "Book Title: ";
cin >> booktitle;
countt = showBooksByTitle(count, booktitle);
cout << countt << " records found." << endl;
break;
case 'S':
showAll(count);
break;
case 'Q':
break;
}
}
//Pause and exit
cout << endl << "Press 'ENTER' to quit";
getchar();
getchar();
return 0;
}
int loadData(string pathname) //loading data into the array of structs
{
ifstream inFile;
inFile.open(pathname);
if (!inFile) {
cout << "Error, could not read into file. Please re-compile." << endl;
system("PAUSE");
exit(1); //if not in file, exit;
}
int i = 0;
while (!inFile.eof()) {
getline(inFile, books[i].title);
getline(inFile, books[i].author);
i++;
}
return i;
}
char switchoutput() //seperate output function to get my characteroutput constantly resetting and returning the uppercase version for my switch
{
char input;
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All: ";
cin >> input;
return toupper(input);
}
int showBooksByAuthor(int count, string name)
{
int authorcount = 0;
authorcount = FindAuthor(count, name);
return authorcount;
}
int showBooksByTitle(int count, string title)
{
int titlecount = 0;
titlecount = FindTitle(count, title);
return titlecount;
}
void showAll(int count)
{
for (int i = 0; i < count; i++)
{
cout << books[i].title << " (" << books[i].author << ")" << endl;
}
}
int FindAuthor(int count, string userinput)
{
int authorcount = 0;
string stringlower, arraylower;
int num;
// called upon function to lowercase any of the user inputs
ConvertStringToLowerCase(userinput, stringlower);
for (int i = 0; i < count; ++i) //this function's count determines at which locations to output the author and names (an argument from books by author)
{
// called upon function to lowercase any of the stored authors'
ConvertStringToLowerCase(books[i].author, arraylower);
num = arraylower.find(stringlower); // searches string for userinput (in the lowered array) and stores its value
if (num > -1) // you can never get a -1 input value from an array, thus this loop continues until execution
{
cout << books[i].title << " (" << books[i].author << ")" << endl; //cout book title and book author
authorcount++; //count
}
}
return authorcount;
}
int FindTitle(int count, string userinput) //same as previous but for titles
{
int titlecount = 0;
string stringlower, arraylower;
int num;
ConvertStringToLowerCase(userinput, stringlower);
for (int i = 0; i < count; ++i)
{
ConvertStringToLowerCase(books[i].title, arraylower);
num = arraylower.find(stringlower);
if (num > -1)
{
cout << books[i].title << " (" << books[i].author << ")" << endl;
titlecount++; //count
}
}
return titlecount;
}
void ConvertStringToLowerCase(const string orig, string& lwr) // I found this from another classmate during tutoring, I thought to be useful.
{
lwr = orig;
for (int j = 0; j < orig.length(); ++j) //when called upon in my find functions, it takes the string and convers the string into an array of lowercase letters
{
lwr[j] = tolower(orig.at(j));
}
}