File Stream problems - c++

In 2010 Visual C++ Express, I'm using
...
ifstream inFile("inputfile.dat");
double number;
while(inFile >> number)
{
cout << number << endl;
}
...to read 8 numbers stored in a file into the program, and show them on the monitor. It shows them all correctly and as needed, but I need to store each individual number as already specified doubles. From top to bottom,
Customer 1's Identification #
Balance
Payments outstanding
Purchases that have been made
then the other 4 numbers are the same thing just for a different customer. I've tried a ton of different ways to do it, but each come with:
"Run-Time Check Failure #3 - The variable 'variableName' is
being used without being initialized."
and it happens with almost all of the variables. I've searched for anything to help me with this but couldn't seem to find something that would help me to the extent of what I needed.

Assuming that you really want to store these in 8 distinct variables, and not in some aggregate data type:
std::ifstream inFile("inputfile.dat");
double number;
if(inFile >> cust1id >> cust1bal >> cust1pay >> cust1purch >>
cust2id >> cust2bal >> cust2pay >> cust2purch) {
std::cout <<
"Customer 1's Identification #: " << cust1id << "\n" <<
"Balance: " < cust1bal << "\n" <<
"Payments outstanding: " << cust1pay << "\n" <<
"Purchases that have been made: " << cust1purch <<
"Customer 2's Identification #: " << cust2id << "\n" <<
"Balance: " < cust2bal << "\n" <<
"Payments outstanding: " << cust2pay << "\n" <<
"Purchases that have been made: " << cust2purch << "\n";
}

Related

How would I print a multi-line (non-standard) unicode string of text in C++? Updated for Clarity! (hopefully)

Rewriting this question with a bit more knowledge on what I'm requesting; (Thank you James Risner and Turtle for your assistance, but I didn't word this correctly and got different responses than what was needed)
I am currently in the process of writing a program for my class in which I print out non-standard Unicode characters in a string. These characters are direct copies from a website, and not in u\ #### standard copy, but rather the unicode characters pre-selected. The program I am running this on is Clion, building my program using mingw's ninja build settings.
My issue that I'm experiencing is that my output, rather than the unicode characters, is instead a random array of (I think) unrelated characters. Printing this in Clion's Debug menu outputs the proper output, but printing it in the runtime or in its own external file all output the issue.
Below is an exact copy of my code (character for character) DO NOT REUSE PLEASE :(
#include <iostream>
#include <string>
#include <windows.h>
#define _WIN32_WINNT 0x0500
#include <thread>
#include <chrono>
#include <random>
using namespace std;
static int Range(int start, int end){
random_device rd;
mt19937 rng(rd());
uniform_int_distribution<int> dist(start,end);
return dist(rng);
}
int main() {
system("color 0F");
HWND consoleWindow = GetConsoleWindow();
int windowSize = 390;
MoveWindow(consoleWindow, windowSize,windowSize,windowSize,windowSize, TRUE); // This program and the one below it not only locks the window size, but also locks the window at a fixed display pixel length/width
SetWindowLong(consoleWindow, GWL_STYLE, GetWindowLong(consoleWindow, GWL_STYLE) & ~WS_MAXIMIZEBOX & ~WS_SIZEBOX);
ShowScrollBar(GetConsoleWindow(), SB_VERT, 0);
string name = "\033[91m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n\033[92m███╗░░░███╗░█████╗░██████╗░███████╗███╗░░██╗██╗\n\033[93m████╗░████║██╔══██╗██╔══██╗██╔════╝████╗░██║██║\n\033[94m██╔████╔██║██║░░██║██║░░██║█████╗░░██╔██╗██║██║\n\033[95m██║╚██╔╝██║██║░░██║██║░░██║██╔══╝░░██║╚████║██║\n\033[96m██║░╚═╝░██║╚█████╔╝██████╔╝███████╗██║░╚███║██║\n\033[91m╚═╝░░░░░╚═╝░╚════╝░╚═════╝░╚══════╝╚═╝░░╚══╝╚═╝\n\033[92m▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀\n";
float balance = Range(1,50000);
float withD, cSelect;
int x = 0;
while (name[x] != '\0') {
cout << name[x] << flush;
this_thread::sleep_for(chrono::milliseconds(1));
x++;
}
Sleep(2);
std::cout << '\n' << endl;
string bottomBar = "\033[93m░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░█░\n";
string systName = "\033[94mModeni Systems LLC";
cout << " ";
cout << systName << "\n";
std::cout << '\n' << endl;
int y = 0;
while (bottomBar[y] != '\0') {
cout << name[y] << flush;
this_thread::sleep_for(chrono::milliseconds(1));
y++;
}
string Input;
cout << "\n \033[92mPlease Input your Name...\n\n ";
getline(cin, Input);
cout << endl;
cout << " Welcome " << Input << "!" << endl;
cout << " Please select a number from the options below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.) View your Balance\n 2.) Make a withdrawal\n 3.) Deposit\n 4.) Customer Support\n 5.) Log Out Securely\n" << endl;
cout << bottomBar << endl;
cin >> cSelect;
while(cSelect != 5){
if(cSelect==1){
cout << "Your current balance is... " << balance << " dollars!\n \n" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.)View your Balance\n 2.)Make a withdrawal\n 3.)Deposit\n 4.)Customer Support\n 5.)Log Out Securely" << endl;
cin >> cSelect;
} else if(cSelect==2){
cout << "Please enter the amount you'd like to withdraw!\n" << endl;
cin >> withD;
if(withD>balance){
cout << "Sorry, you do not have that much money! Please try again... " << endl;
} else if(withD<=balance) {
balance = balance - withD;
cout << "Successfully taken out " << withD << " dollars!\n" << "Your new balance is " << balance << " dollars!" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << " 1.)View your Balance\n 2.)Make a withdrawal\n 3.)Deposit\n 4.)Customer Support\n 5.)Log Out Securely" << endl;
cin >> cSelect;
}
} else if(cSelect==3){
cout << "Please enter the amount you'd like to deposit!" << endl;
double depAm;
cin >> depAm;
balance = balance + depAm;
cout << "Your new balance is now " << balance << " dollars!" << endl;
cout << "Please select a number from the options given below!\n" << endl;
cout << bottomBar << endl;
cout << "1.)View your Balance\n2.)Make a withdrawal\n3.)Deposit\n4.)Customer Support\n5.)Log Out Securely" << endl;
cin >> cSelect;
} else if(cSelect==4){
cout << bottomBar << "\n" << endl;
cout << "Hello! This is Modeni's Self-Service Assistant!\n Please describe your problem below! \n" << endl;
string proB;
cin >> proB;
int chatF;
chatF = Range(0,5);
if(chatF==0){
cout << "We're so sorry to hear that! Please wait as we get you in touch with someone who can help.\n" << endl;
} else if(chatF==1){
cout << "Sorry to hear that you're currently having that problem! Please sit tight as we get you in touch with someone who can help.\n" << endl;
} else if(chatF==2){
cout << "That's not good! Please wait just a moment as we get you in touch with someone who can help.\n" << endl;
} else {
cout << "Ouch! Just give us a moment while we put you in touch with someone who can help!\n" << endl;
}
Sleep(10000);
string nameSt;
int nameVar;
nameVar = Range(0,5);
if(nameVar == 1)
nameSt = "Raphael";
else if(nameVar == 2)
nameSt = "Marie";
else if(nameVar == 3)
nameSt = "Joesph";
else
nameSt = "Marian";
cout << " \033[94m░█░█ " << nameSt << " has joined the chat █░█░" << endl;
Sleep(Range(3000,8000));
cout <<"\n >> Just a moment while I look over your concern.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Alright. I'm sorry you're dealing with this problem right now. Let's put you in touch with one of our call-in agents to assist you further.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Their number is - 1-(918)-335-1300.\n" << endl;
Sleep(Range(3000,8000));
cout << " >> Is there anything else I can help you with today? \n" << endl;
return 0;
}
}
return 0;
}
I am specifically writing this program for windows, and I have yet to find a solid fix without re-writing the entirety of my code.
The intended output is photograph 1, and the actual output is photograph 2. Any and all help is appreciated!
Photograph 1
Photograph 2
There is no problem with your program. There is a problem with your display.
% cc -o modeni modeni.cpp -lc++
% ./modeni
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
███╗░░░███╗░█████╗░██████╗░███████╗███╗░░██╗██╗
████╗░████║██╔══██╗██╔══██╗██╔════╝████╗░██║██║
██╔████╔██║██║░░██║██║░░██║█████╗░░██╔██╗██║██║
██║╚██╔╝██║██║░░██║██║░░██║██╔══╝░░██║╚████║██║
██║░╚═╝░██║╚█████╔╝██████╔╝███████╗██║░╚███║██║
╚═╝░░░░░╚═╝░╚════╝░╚═════╝░╚══════╝╚═╝░░╚══╝╚═╝
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
% echo $TERM
xterm-256color
I am using a macOS system and this works with TERM=xterm-256color on both iTerm2 and Terminal.
What is TERM?
This environment variable advises applications what terminal emulation is required to display characters on screen properly. An application will use the termcap/terminfo database to look up the proper escape sequences to display colors, move or manipulative text on screen, and other effects.
I only ever see xterm-256color now. Why?
Modern terminal applications assume the output will be in xterm-256color format. Many no longer have an option to choose another format.
AFAIK there is no standard way in C++ to process unicode in standard io, and different OSs' default consoles will behave differently if you just make the unicode string as std::string to output; E.g. in Windows cmd maybe you need _setmode(_fileno(stdout), _O_U16TEXT); to show UTF-16 strings correctly.
Good news is that in C++23 there will be <print> to (hopefully, not definitely so far) help solve this troublesome problem.

Selecting an array value using a random number generator

its a text based monopoly game where i need the dice to select the number from the array like on a board.
I have the number generator, what i need to do though is when the value comes up it pluses it on the array to get the matching number so for example if the players rolls a 6, the 6 + array 0 = array value 6 which will be a name of a street but it means the player knows which place on the made up board they are on. here is the coding i am using to try and do so but i keep on getting 006ff65 what ever. i how can i get it for showing just the number as the names will be added later.
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
As far as I know, you should use srand (time(NULL)); between every call to rand() to correctly return a new random number from every call.
"srand" initialize the random number generator using a seed. In this case seed is time, which should be different on every call.
Pretty basic. You either made a few typos or need to learn how arrays work (and program flow, and subroutines, but perhaps that is for later lessons.)
First you are assigning the result of the array lookup back into your random number: rnum = values[rnum]; which is not a big deal except you use that variable later and it no longer contains what you may think it does. It actually contains the value you are looking for!
Second the variable values is a pointer to the head of your array so you are outputting the address of the values array with this line: cout << "# You move to grid "<< values << endl; there is no array look up happening at all here. It is strange you missed that because you did reference the array contents properly when you replaced the random number value earlier.

How do I get multiple lines of strings and integers to read from and input file and display in C++?

I have been given and assignment to read a file of data listed below:
Turn on the Bright Lights
Interpol
9.49
House of Jealous Lovers
The Rapture
1.29
Fever to Tell
Yeah Yeah Yeahs
6.99
Desperate Youth, Blood Thirsty Babes
TV on the Radio
8.91
The Fragile
Nine Inch Nails
12.49
Input this data into C++ and then display in a matrix and output total price of the cd's and how many cd's were sold. So far I can only get the first line to display properly and cannot figure out what I need to change to get the rest to display. Here is what I have written thus far. I have not started on the output code and feel as though I will not have an issue with that.
#include<iostream>
#include<fstream>
#include<iomanip>
#include<string>
using namespace std;
int main()
{
ifstream inputFile, processLine;
ofstream outputFile;
string title, band;
double price, total = 0;
inputFile.open("orders.txt");
while (!inputFile.eof())
{
getline(inputFile, title);
getline(inputFile, band);
inputFile >> price;
total += price;
cout << "Welcome to Megan McCracken's Online Music Store" << endl;
cout << "You have submitted the following order:" << endl;
cout << "***************************************************************************" << endl;
cout << "Title" << setw(46) << "Artist" << setw(24) << "Cost" << endl;
cout << title << setw(28) << band << setw(22) << fixed << setprecision(2) << price << endl;
cout << title << setw(30) << band<< setw(19) << fixed << setprecision(2) << price << endl;
cout << title << setw(20) << band << setw(20) << fixed << setprecision(2) << price << endl;
cout << title << setw(20) << band << setw(20) << fixed << setprecision(2) << price << endl;
cout << title << setw(20) << band << setw(20) << fixed << setprecision(2) << price << endl;
cout << "--------------------------------------------------------------------------" << endl;
cout << "Total Due:" << setw(75) << fixed << setprecision(2) << total << endl;
cout << "==========================================================================" << endl;
}
/* getline(inputFile, title);
cout << left << title;
getline(inputFile, band);
cout << setw(23) << band;
inputFile >> price;
cout << setw(10) << fixed << setprecision(2) << price << endl; */
system("pause");
return 0;
}
There are multiple problems with this code.
while (!inputFile.eof())
This is always a bug. See the linked article for more information.
But this is not the only problem.
getline(inputFile, band);
inputFile >> price;
Do not use both std::getline() and operator>> on the same input stream. operator>> has certain, narrowly-constrained, semantics when it comes to handling whitespace. Here, operator>> is not going to consume the trailing newline, so on the next loop iteration the first getline() is going to go off the rails.
Although there are some band-aid fixes that are often suggested, in this case, the simplest solution is to simply not use operator>>.
Use getline() a third time, to read the third line into a std::string. Then using it to construct an independent std::istringstream, and use operator>> with that. Problem solved.
After fixing that, there are some logical errors that need to be fixed. The header of the report should likely be displayed before the loop, and inside the loop the only thing that should be done is displaying a single line of the receipt, and adding up the totals, then displaying the total after the end of file was received.

How to print the contents of the C++ keyboard/cin buffer to the console without modification?

I've been working on a program that does quite a bit (at least for me) with cin and its functions, and I've been having a hard time keeping track of what's in the keyboard buffer throughout the program. It's causing me some errors - I was wondering if there was a function or a technique I could use to print the contents of the cin/keyboard buffer to the screen so that I could know what's in it at that point in the program.
I've attached the source code for anyone who's interested. It's homework for one of my classes, so apologies for anyone who sees this as too easy to even bother asking.
// CHAPTER 4 HOMEWORK - PROBLEM 16 - RUNNING THE RACE
/* Write a program that asks for the names of three runners and
the time it took each of them to finish a race. The program
should displace who came in first, second, and third place.
Input validation: only accept positive numbers for the times*/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// Introduction for the user
cout << "\t\t\t ~ RUNNING THE RACE ~\n"
<< "\t\t\t --------------------\n\n"
<< "Welcome! In this program, you can enter the names of three runners,\n"
<< "and the times at which they finished a race. The program will organize\n"
<< "the names and times from first to last.\n\n"
<< "Are you ready to begin?\n"
<< "Press the Enter key to continue . . . ";
cin.get();
// declare variables and string objects
string runnerName1, runnerName2, runnerName3;
int minutes1, minutes2, minutes3;
double seconds1, seconds2, seconds3;
// RUNNER 1
cout << "\nFirst we'll deal with runner 1.\n"
<< "Please enter runner 1's full name: ";
getline(cin, runnerName1);
cout << "Okay! Now for " << runnerName1 << "'s time.\n"
<< "First, enter " << runnerName1 << "'s minutes (a whole number): ";
cin >> minutes1;
cout << "And now enter " << runnerName1 << "'s seconds: ";
cin >> seconds1;
// RUNNER 2
cout << "\nNext we'll deal with runner 2.\n"
<< "Please enter runner 2's full name: ";
cin.ignore(); // because of the remaining space in the keyboard buffer leftover from the last cin >> statement
getline(cin, runnerName2);
cout << "Good! Now for " << runnerName2 << "'s time.\n"
<< "Enter " << runnerName2 << "'s minutes (a whole number): ";
cin >> minutes2;
cout << "Now enter " << runnerName2 << "'s seconds: ";
cin >> seconds2;
// RUNNER 3
cout << "\nFinally, runner 3.\n"
<< "Please enter runner 3's full name: ";
cin.ignore();
getline(cin, runnerName3);
cout << "What is " << runnerName3 << "'s time?\n"
<< "First, enter " << runnerName3 << "'s minutes (a whole number): ";
cin >> minutes3;
cout << "Now enter " << runnerName3 << "'s seconds: ";
cin >> seconds3;
// display the gathered data in a useful manner
cout << "___________________________________________\n" // border
<< "RESULTS:\n\n"
<< "NAME:\t\t\tTIME:\n";
// make sure any extra seconds entered above 60 gets added to the number of minutes
while (seconds1 >= 60.0)
{
seconds1 -= 60.0;
minutes1 += 1;
}
while (seconds2 >= 60.0)
{
seconds2 -= 60.0;
minutes2 += 1;
}
while (seconds3 >= 60.0)
{
seconds3 -= 60.0;
minutes3 += 1;
}
// now for the results . . .
cout << runnerName1 << "\t" << minutes1 << ":" << seconds1 << endl;
cout << runnerName2 << "\t" << minutes2 << ":" << seconds2 << endl;
cout << runnerName3 << "\t" << minutes3 << ":" << seconds3 << endl;
cin.ignore();
cin.get();
return 0;
}
Also, this was built on VS 2012 Express, for anyone who has multiple versions. I didn't use any windows-exclusive code within the program though (eg system("pause")), so it should work fine with other compilers.

Check for non-numeric inputs in a C++ program

How do you check for non-numeric input using C++? I am using cin to read in a float value, and I want to check if non-numerical input is entered via stdin. I have tried to use scanf using the %d designator, but my output was corrupted. When using cin, I get the correct format, but when I enter, a string such as "dsffsw", I get an infinite loop.
The commented code was my attempt to capture the float, and type cast it as string, and check if it is a valid float, but the check always comes up false.
I have tried using other methods I have found on the message boards, but they want to use scanf in C and not cin in C++. How do you do this in C++? Or in C if it is not feasible.
while (!flag) {
cout << "Enter amount:" << endl;
cin >> amount;
cout << "BEGIN The amount you entered is: " << strtod(&end,&pend) << endl;
//if (!strtod(((const char *)&amount), NULL)) {
// cout << "This is not a float!" << endl;
// cout << "i = " << strtod(((const char *)&amount), NULL) << endl;
// //amount = 0.0;
//}
change = (int) ceil(amount * 100);
cout << "change = " << change << endl;
cout << "100s= " << change/100 << endl;
change %= 100;
cout << "25s= " << change/25 << endl;
change %= 25;
cout << "10s= " << change/10 << endl;
change %= 10;
cout << "5s= " << change/5 << endl;
change %= 5;
cout << "1s= " << change << endl;
cout << "END The amount you entered is: " << amount << endl;
}
return 0;
}
int amount;
cout << "Enter amount:" << endl;
while(!(cin >> amount)) {
string garbage;
cin.clear();
getline(cin,garbage);
cout << "Invalid amount. "
<< "Enter Numeric value for amount:" << endl;
}
I think you task relates to the so called defensive programming, one of it`s ideas is to prevent situations like one you described (function expects one type and user enters another).
I offer you to judge whether input is correct using method that returns stream state , which is good(),
so I think it will look something like this:
int amount = 0;
while (cin.good()) {
cout << "Enter amount:" << endl;
cin >> amount;