How To Find Specific Data From A Text File and Change It? - c++

I'm new to programming and I'm trying to change this code to write it to a text file.
Basically I have to find the price of an item that was stored in the array 'List', each pointer contains an item code, description, price and discount.
I'm having two problems though, finding the item's price in the text file and than changing it by the user's input.
void DoSetItemPrice(void)
{
int `searchCode` = 0;
double changePrice = 0.00;
cout << "Enter Code For Search: ";
cin >> searchCode;
cout << endl;
cout << "Enter Price Change: $";
cin >> changePrice;
cout << endl;
for (int i = 0; i < numItems; i++)
{
if (List[i].HasCode(searchCode) == true)
{
List[i].SetPrice(changePrice);
cout << "New Price: $" << List[i].GetDiscount();
} else
cout << "The Code You Entered Could Not Be Found";
}
}

i had this kind of situation before but my solution was kinda bad but here it is anyways,i don't know any pre defined functions in C++ that helps with string manipulation, but u can try entering a character before the price like 'ù' for example ,if the price is 100$ the string would become "ù100$" then based on that u can use a loop to check the text file u are reading and when ever u encounter the character 'ù' that means what comes after it is the price so u convert that part into numbers until u reach the '$' character which indicates the end of the price.

Related

c++ User input validation in sorted array

Hello i have a assinment that im making a weater program where we ask the user to enter info
first enter how many citys to use
then enter city name and degrees
then i will print out the list in order starting with the coldest city
and last i need to add a search funkar to search by degrees to find a location with that degrees
this one i havent started with
but my MAIN problem is that i need to validate that the user input is between -60 and 60 when enter the city and degrees... i just dont get it to work with anything... can someone please help out?`
cout<<"Enter Name of City and degrees \n\n";
for(i=0;i<n;i++){
cout<<"---------\n";
cin>>s_array[i].name;
cin>>s_array[i].degrees;
this is the code where user put in city and degree EX Rio 50
i just dont know how to validate it to be between -60 and 60`
What you're looking for, is simple data validation.
Assuming you have a struct City:
// used to hold the data
struct City {
string name;
double degrees;
};
and in your main(), you have initialised an array of these structs:
bool temperatureValid(const City);
int main() {
const int32_t totalCities = 12;
City cities[totalCities];
for (int32_t i = 0; i < totalCities; i++) {
// add data to structs
cout << "Enter city name: ";
cin >> cities[i].name; // you might want to validate this, too
cout << "Enter temperature: ";
cin >> cities[i].degrees;
cout << cities[i].name << " has a temperature of " << cities[i].degrees << "°" << endl;
if (temperatureValid(cities[i])) {
// cool... or not
} else {
cerr << "Invalid temperature range!" << endl;
--i; // make sure we can do this one again
continue;
}
}
return 0;
}
bool temperatureValid(const City city) {
return city.degrees >= -60 && city.degrees <= 60;
}
First of all, you should create a class. I understand from your code you must use class. If you don't have to it is easier than this. Then you should create an object.
Basic logic below here. You should create a class well.
class Weather //create class
Weather city // create object
cout<<"Please enter a city name:"<<endl;
cin>>city.name;
cout<<"Please enter a city degree:"<<endl;
cin>>city.degrees;

C++, an if loop for an assignment

I need some help trying to figure out a way to make an if statement taking the users input after a category is typed in. If the user types in string categories[0] in the cin statement, which in this case is "Number of drivers involved in fatal collisions per billion miles." I want it to display the first sentence from the worststate[0] array, which in this case will be North Dakota and South Carolina. I need help doing that for every category, to match up with the state listed, it goes in order.
#include <iostream>
using namespace std;
string worstState[7] = {
{"North Dakota and South Carolina"},
{"Hawaii"},
{"Montana"},
{"District of Columbia"},
{"District of Columbia and Mississippi"},
{"New Jersey"},
{"Louisiana"},
};
void displayIntro(){
cout << "Welcome to the Car Accident Statistic Website" << endl;
cout << "Take a look at the following categories: " << endl;
}
string categories[7] = {
{"Number of drivers involved in fatal collisions per billion miles"},
{"Percentage of drivers involved in fatal collisions who were speeding"},
{"Percentage of drivers involved in fatal collisions who were Alcohol-Impaired"},
{"Percentage of drivers involved in fatal collisions who were not distracted"},
{"Percentage of drivers involved in fatal collisions who had not been involved in any previous accidents"},
{"Car Insurance Premiums"},
{"Losses incurred by insurance companies for collisions per insured driver"},
};
int main(){
string Input;
displayIntro();
cout << categories[0] << endl;
cout << categories[1] << endl;
cout << categories[2] << endl;
cout << categories[3] << endl;
cout << categories[4] << endl;
cout << categories[5] << endl;
cout << categories[6] << endl;
cout << "Enter a category: ";
cin >> Input;
if (Input == categories....
return 0;
}
Obviously the code isn't the best organized, which I'm still gonna work on, but I just want the user to type in the category string, and for the state to match up with that specific category in the categories array, all in order based on the way they are entered.
Wondering what the best way to go about this situation is
You can use an unordered_map (aka hash table):
Initialize the map at the start of your program that maps all the questions to their respective answers (i.e. categories[i] to worstState[i]).
unordered_map<string, string> questionsToAnswers;
for (size_t i = 0; i < 7; i++) {
questionsToAnswers[categories[i]] = worstState[i];
}
When the user types a string in, you can look up the answer like this:
string s;
cin >> s;
auto itor = questionsToAnsers.find(s);
if (itor != questionsToAnswers.end()) {
cout << itor->second;
} else {
// question not found in map
}
If I understand correctly if the user inputs in categories[0], you want to display worstState[0], if the user inputs in catergories[1], you want to display worstState[1], and so on. Now it looks like your input is fixed which means you can use a switch statement, however because there are a fairly large number of courses you want to consider a for loop probably would look more clean.
So something like:
for(int i = 0; i < size(categories); i++){
if(Input == categories[i]){
cout << worstState[i] << endl;
}
}

Transversing an Array of structs error in C++

Current code:
const int MAX_CODENAME = 25;
const int MAX_SPOTS = 5;
struct Team {
string TeamName[MAX_CODENAME];
short int totalLeagueGames;
short int leagueWins;
short int leagueLoses;
};
//GLOBAL VARIABLES:
Team league[MAX_SPOTS];
void addTeams(){
int i = 0; //first loop
int j; //second loop
while(i < MAX_SPOTS){
cout << "****** ADD TEAMS ******" << endl;
cout << "Enter the teams name " << endl;
scanf("%s", league[i].TeamName) ;
}
void searchTeam(){
string decider[MAX_CODENAME];
cout << "Please enter the team name you would like the program to retrieve: " << endl;
cin >> decider[MAX_CODENAME];
for(int i = 0; i < MAX_SPOTS; i++){
if(decider == league[i].TeamName){
cout << endl;
cout << league[i].TeamName << endl;
break;
}else{
cout << "Searching...." << endl;
}
}
}
I really dont know why its not working but I have included all the perquisite header files such as and but the program crashes when i enter the data and then attempt to search. I get the circle of death and then program not responding then says Process returned 255 (0xFF) . It does not even out put Searching.... the program practically gives up as soon as I enter that name.
Also if this can be optimized by the use of pointers that would be great.
tl;dr run-time error causing the search to fail as soon as i type in a name. And for the record I have checked to make sure the name I entered is valid.
scanf doesn't know about std::string. Use std::cin >> league[i].TeamName.
scanf("%s", league[i].TeamName) ;
This should be changed to
std::cin >> league[i].TeamName ;
A couple of other things here....
string decider[MAX_CODENAME];
cout << "Please enter the team name you would like the program to retrieve: " << endl;
cin >> decider[MAX_CODENAME];
Every time you input a value, you are telling the computer to hold the inputted value at decider[25] but the computer only reads indexes 0-24.
if(decider == league[i].TeamName){
Which array slot are you comparing the team name to? If its the 25th element than the statement should be
if(decider[24] == league[i].TeamName){
Pointers are better suited if the number of TeamNames are unknown. Based on the limited code presented, I highly recommend you stay within the realm of basic data types. For the purposes of troubleshooting, please post your full code in the future.
Your TeamName member variable:
string TeamName[MAX_CODENAME];
is an array of 25 strings, so in this line:
scanf("%s", league[i].TeamName) ;
you are courrupting the array. You don't really want an array anyways, so change the TeamName declaration to:
string TeamName;
and then when you read the name, you'll need to use iostreams which knows how to populate a string type (scanf only works with c char arrays):
std::cin >> league[i].TeamName

C++ Array not taking correct input from file

Disclaimer: I am a beginner to programming, so what I say might sound really stupid
I have to make a "Telephone Directory" for school. The program isn't complete, but there are some things that I need to fix before moving on. The array TelephoneNumbers either isn't storing the numbers from the file correctly, or isn't displaying them. For the SeaerchRecords function, the first number in the file is displayed correctly, the second is displayed as "2147483647," and the rest of the numbers display as "0." The modify function also doesn't change the number, and I confirmed this with the while in the function. The string array works perfectly fine, however. May someone explain what I'm doing incorrectly?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string TelephoneNames[100];
int TelephoneNumbers[100];
void ModifyRecords(); //Function to Modify Records
void SearchRecords(); //Function to Search Records
void DeleteRecords(); //Function to Delete Records
int main()
{
fstream inputFile;
fstream outputFile;
char choice;
inputFile.open("Telephone Names.txt"); //To store
for (int count=0;count<100;count++) //file names
{ //into a
inputFile >> TelephoneNames[count]; //string
}
inputFile.close();
inputFile.open("Telephone Numbers.txt");//To store
for (int count=0;count<100;count++) //file #'s
{ //into a
inputFile >> TelephoneNumbers[count];//string
}
inputFile.close();
//Display options available
cout << " Hello, do you want to:\n";
cout << " ======================\n";
cout << "-Modify Records|Enter M\n";
cout << "-Search Records|Enter S\n";
cout << "-Delete Records|Enter D\n";
//Store choice
cin >> choice;
//Send to different function
if (choice=='M'||choice=='m')
{
ModifyRecords();
}
if (choice=='S'||choice=='s')
{
SearchRecords();
}
return 0;
}
void ModifyRecords()
{
string name;
string newname;
int newnumber;
int count=0;
cout << "Enter the name of the person: ";
cin >> name;
for (count=0;TelephoneNames[count]!=name;count++)//To determine where in the strings the new numbers need to be
{
}
cout << "Enter the new name of the person: ";
cin >> newname;
cout << "Enter the new number of the person: ";
cin >> newnumber;
TelephoneNames[count]={newname};
TelephoneNumbers[count]={newnumber};
count=0;
while (count<6)
{
cout << TelephoneNames[count] << endl;
cout << TelephoneNumbers[count] << endl;
cout << endl;
count++;
}
}
void SearchRecords()
{
string name;
int count=0;
cout << "Enter the name of the person you would like to find: ";
cin >> name;
for (count=0;TelephoneNames[count]!=name;count++)//To determine where in the strings the new numbers need to be
{
}
cout << "Name: " << TelephoneNames[count] << endl;
cout << "Number: " << TelephoneNumbers[count] << endl;
}
Since there is no any answer still and I don't see exactly the problem at this point I'll provide some suggestions how you can find a problem in your code.
In any programming situation when you can't find a bug, first task is to locate it as much precisely as you can and check all input data and assumptions. Usually, debugger is used for such purposes, but you can just output text in console before creating final version of your program.
To start with, you must check that you really received names and telephones from your file:
inputFile.open("Telephone Names.txt"); //To store
for (int count=0;count<100;count++) //file names
{ //into a
inputFile >> TelephoneNames[count]; //string
cout << TelephoneNames[count] << endl; //WE MUST SEE WHAT IS REALLY STORED IN TelephoneNames
}
inputFile.close();
inputFile.open("Telephone Numbers.txt");//To store
for (int count=0;count<100;count++) //file #'s
{ //into a
inputFile >> TelephoneNumbers[count];//string
cout << TelephoneNumbers[count] << endl; //WE MUST SEE WHAT IS REALLY STORED IN TelephoneNumbers
}
inputFile.close();
Ok, when it is checked and you are defenitely sure there is no problem in your data we can move to SeaerchRecords function doing the same procedure. We must check what is happening while you are searching:
for (count=0;TelephoneNames[count]!=name;count++)//To determine where in the strings the new numbers need to be
{
cout << "Search step: " << count << " name " << name << " found name " << TelephoneNames[count] << " number " << TelephoneNumbers[count] << endl;
}
Doing so you will locate your bug rather quickly. The problem can be in input files format, in difference of "name" and stored names format etc.
I'll provide several additional suggestion how you can improve your code.
1) Try to use const declarations for such commonly used things as number of records (const int NUMBER_OF_RECORDS = 100; insted of just putting '100' everywhere), it will reduce the amout of work and possible bugs. 2) Try to check all possible problems that you program can encounter if someting is wrong with data. What will happen if you have less than 100 records in your files now? Program crush or silent reading of unappropriate data which is even worse. Check that you haven't reach file end on any step of reading along with current check that you've reached you number of records and do something in case of unappropriate data.
3) Check the possible problems with conditions in your cycles not to run them infinite number of times. Now your condition for(count=0;TelephoneNames[count]!=name;count++)
will execute forever if there is no such name or just crush the program on count 100 or more. You should check that count doesn't exceed that value. Good luck!

do loop statement is causing an infinite loop

I am writing a library program that displays a menu of options letting the user add new books to the library, but in my add statement it accepts the title and then gets caught in an infinite loop. I wrote a book class that mainly uses pointers to assign things, if I need to post that I will. But when you run the program it compiles, displays the menu, and when you choose add a book it accepts the title but as soon as you hit enter it starts an a infinite loop.
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
int main()
{
int bookCounter = 0;
Book library[25];
int menuOption = 0;
char tempt[50] = "\0";
char tempauth[50] = "\0";
char search[50] = "\0";
unsigned int tempp = 0;
do
{
menuOption = 0;
cout << endl << "1. Show the Library" << endl;
cout << "2. Add a Book" << endl;
cout << "3. Search the Library by Title" << endl;
cout << "4. Exit Library" << endl;
cout << "Select a menu option (e.g. 1, 2, etc.): ";
cin >> menuOption;
if(menuOption == 1)
{
for(int i = 0; i < bookCounter; i++)
{
library[i].displayBook();
}
}
else if(menuOption == 2)
{
cout << "Enter the Title: ";
cin >> tempt[50];
cout << endl << "Enter the Author's name: " ;
cin >> tempauth[50];
cout << endl << "How many pages does the book have? (just enter a number, e.g. 675, 300): ";
cin >> tempp;
library[bookCounter].setAuthor(tempauth);
library[bookCounter].setTitle(tempt);
library[bookCounter].setPages(tempp);
bookCounter++;
menuOption = 0;
}
else if(menuOption == 3)
{
cout << "Enter a title you would like search for (will return partial matches): ";
cin >> search[50];
for (int i = 0; i < bookCounter; i++)
{
int temp = strcmp(search, library[i].getTitle());
if (temp == 1)
{
library[i].displayBook();
}
}
}
}while(menuOption != 4);
system("pause");
return 0;
}
The problem is caused by the way you are trying to read into the arrays:
cin >> tempt[50];
This tries to read a single character into the character at index 50 of the array tempt, which is outside the bounds of the array (which has valid indices in the range [0,49]).
This means only the first character of the entered title will be consumed from the output. Similarly for author. Hence, only the first two characters which you have entered are actually read. Then, this line will be encountered:
cin >> menuOption;
Here, what is left in the buffer (the remainder of the title) will be read, expecting a number. As this does not match a valid format for a number, you will get an error flag in cin. This will mean that all resulting inputs will also fail, menuOption will never change and your program gets stuck in a loop.
A solution to your problem would be to read into tempt without index. You can also check if a read has failed using if(cin.fail()) which should only trigger if there's been an error. If so, handle it and then call cin.clear() to reset the error flags.
I think that this line cause the problem,
cin >> search[50];
You're accessing out bound of search array.
One error is when you type in the menu option, the 'return' stays in the input buffer. The next read of char[] in your tempt variable, will be skipped.
Type cin.ignore(); after cin >> menuOption;
Also, you should read tempt instead instead of tempt[50].
This
cin >> tempt[50];
accesses a non-existent entry in the array. You probably meant to code
cin >> tempt;
Or, better, use std::string instead of raw char array.