Program will not print line before exit() function? - c++

I have a little project for school I am writing in C++, and we have to account for some error and just exit the program in the event that it happens. Basically, in the else statement when the expression is evaluated as false, it's like it won't write to the file the error. If I output it to the console (via cout) instead of writing it to the file it works just fine, but when I try to write it to the output file, it does not work. Basically, that is my question. My professor is requiring that all output is to the file, that's why I can't use cout. So why will it output it to the console, and not to the file?
P.S. I am outputting other stuff to the file and it's working fine, so for the record I think it is narrowed down to the little block of code in the else statement.
if(tempUnit == 'C' || tempUnit == 'F')
{
if(tempUnit == 'F')
{
temp = convertTemp(temp, tempUnit);
}
temps[a] = temp;
printTemp(outputFile, tempUnit, temp);
printTimestamp(outputFile, humanDate);
outputFile << endl;
}
else{
// this is where it doesnt work
outputFile << "Error. Incorrect temperature unit, must be " <<
"either a capital C or a capital F. Program ended.";
exit(0);
}

You need to flush the buffer before exiting the program.
outputFile << "Error. Incorrect temperature unit, must be either a capital C or a capital F. Program ended." << std::flush;
or
outputFile << "Error. Incorrect temperature unit, must be either a capital C or a capital F. Program ended." << std::endl;

Both stdout and stderr are buffered. You need to tell your program to flush your output file.
If you were doing C, you would,
fflush(stdout);
//or
fflush(stderr);
Since you are doing C++, you spell fflush, endl,
cout << std::endl; // endl does the flushing
see this stackoverflow: endl

Related

Understanding why unwanted iterations of a cout statement occur [duplicate]

This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 3 years ago.
I am working with some C++ code. I have a while-loop set up to allow me to run through some code x-number of times. The while loop terminates once the user indicates that they do not want to run through the code again.
#include <iostream>
#include <string>
using namespace std;
char request;
int main() {
while (request != 'N')
{
string getCode = "";
while (getCode.length() != 3)
{
cout << "Please enter your container's region code (A or B followed by two-number identification)" << endl;
getline(cin, getCode);
if (getCode.length() != 3)
{
cout << "Error" << endl;
}
}
//clear the screen
system("cls");
//get letter
if (getCode.at(0) == 'A' || getCode.at(0) == 'B')
{
if ((getCode.at(1) >= '0' && getCode.at(1) <= '9') && (getCode.at(2) >= '0' && getCode.at(2) <= '9'))
{
if (getCode.at(0) == 'A')
{
cout << "The shipping charge is $25" << endl;
}
else if (getCode.at(0) == 'B')
{
cout << "The shipping charge is $30" << endl;
}
}
else
{
cout << "Error" << endl;
}
}
else
{
cout << "Error...Please enter the code as A or B followed by two numbers" << endl;
}
//Again?
cout << "Would you like to enter in another shipping identification number?" << endl;
cin >> request;
}
cout << "Thank you" << endl;
//End Program
system("pause");
return 0;
}
When I indicated that yes (entering 'Y' to the 'Would you like to enter in another shipping identification number question') I would like to run through the code again, the program outputs an unwanted 'Please enter your container's region code (A or B followed by two-number identification' and 'error' statement. Also please note, the code is inside 'int main()' and that I have properly formatted my 'include' statements.
Your question is to understand why this is happening, so here's the explanation. The code you wrote states thusly:
string getCode = "";
while (getCode.length() != 3)
{
cout << "Please enter your container's region code...
As you see, getCode is always initialized to an empty string. Immediately afterwards, if its length is not 3, this question is outputted.
You need to understand that your computer will always do exactly what you tell it to do. Your computer will not do what you want it to do, but only what you tell it to do. The above is what you told your computer to do, and your computer will always obediently follow its strict instructions, every time it runs this code. That's pretty much the explanation, and there's nothing more to understand.
This section of code is inside another loop, and you indicated that you do not wish the prompt to appear on second and subsequent iteration of the loop, only on the initial one.
However, there's nothing in your instructions to your computer, above, that specify this. You didn't tell your computer that this is what it should do, so why do you expect your computer to do that, entirely on its own? Every time your computer executes these statements shown above, this is exactly what will happen. Nothing more, nothing less. Whether it's the first time inside the outer while loop, or on each subsequent time the while loop iterates, it doesn't matter. The code always does exactly the same thing: getCode gets created and set to an empty string, and because its length is not 3, the inner while loop runs, prints the prompt and calls std::getline to read a line of text from std::cin. At the end of your while loop, if your instructions to your computer indicate that it should run the code in the while loop again, from the beginning (because that's what the while loop does), then the above instructions get executed.
If you now understand why your computer does this (because that's what you told it to do), then you should easily figure out what to tell your computer so it doesn't do this. If you want your computer to print the prompt only the first time it executes the while loop, then this is exactly what you need to tell your computer: set a flag before the while loop, print the prompt only if the flag is set (with all other existing logic remaining the same), and then clear this flag afterwards, so the next time the while loop runs, your computer will do exactly what you told it to do, and not print the prompt.
when I indicate 'Y' to the prompt 'Would you like to enter in another shipping identification number?', it outputs the following: 'Please enter your container's region code (A or B followed by two-number identification)' 'error' 'Please enter your container's region code (A or B followed by two-number identification' . When I input 'Y' I only want it to output 'Please enter your container's region code (A or B followed by two-number identification)'...I only want it to output once
Now that I understand your question, what's happening is an newline (\n) is getting added to the std::cin buffer at these lines right here:
//Again?
cout << "Would you like to enter in another shipping identification number?" << endl;
cin >> request;
This makes even more sense especially when combined with your other comment:
Before int main() there should be a 'char request;
So request a single char. That means when you type something like this:
Y
The newline is added to std::cin as well. That can't be stored in a single char, and the >> may not remove it either. That means it's just sitting here.
What this does is when you get to your if statement at the beginning of the loop again:
while (request != 'N')
{
string getCode = "";
while (getCode.length() != 3)
{
cout << "Please enter your container's region code (A or B followed by two-number identification)" << endl;
getline(cin, getCode);
if (getCode.length() != 3)
{
cout << "Error" << endl;
}
}
getline() sees the newline you added previously and instantly returns an empty string. Empty strings have a length of 0, so it fails your if statement, which prints the error.
The solution is simple, just tell std::cin to ignore the newline:
//Again?
cout << "Would you like to enter in another shipping identification number?" << endl;
cin >> request;
cin.ignore(1, '\n');

How do I pause my command window when using the exit function in C++?

When a user types something, I want my function to stop and display a phrase. My program currently closes out the command window when the user types that specific something, but I want it to pause so the user can see the phrase. Below is my code in question:
if (in.peek() != '/')
{
obj = Rational(top);
cout << "Bad input format for operator >>. Aborting!" << endl;
exit(1);
}
Typically a nice way to achieve that is:
std::cout << "Press enter to continue" << std::endl;
std::cin.ignore();

My files are never opening?

Whenever I try to make a program based on files, my program is never able to open the file itself.
It always ends up executing the part of the program in the "else" part. Is it because my file might not be in the same directory? If so, how do I find the location of my file? Here's the code. I just wanted to check if its working fine or not by inputting and outputting the strings using the concept of files.
int main()
{
char str1[20], str2[20];
FILE *pFile;
pFile = fopen("Rocket.txt", "r+");
if (pFile != NULL) {
while (feof(pFile)) {
cout << "Enter String 1: " << endl;
fgets(str1, 20, pFile);
cout << "Enter String 2: " << endl;
fgets(str2, 20, pFile);
cout << "The Strings input are: " << endl;
fputs(str1, pFile);
fputs(str2, pFile);
}
}
else {
cout << "File not opened." << endl;
}
1) "How do I find the location of my file?"
right-click on your file
properties->Details->Folder path or
properties->General->Location
For example if it was C:\Users\user\Desktop then the location you write is c:\\Users\\user\\Desktop\\Rocket.txt
2) In your code, I found two bugs
Notice that in the "while condition" you should write (feof(pFile)==0) or (!feof(pFile)) because it should continue reading from file until it reaches the end of file and feof(pFile) == 1.
"puts" writes at the end of the file. So when the file marker is not at the end of the file, it doesn't write on it, unless your initial file has just 37 characters. So it's not a good idea to use "puts" in this program. Instead , you can use cout to check out values of str1 and str2.

I am trying to end my C++ program when the user presses 'Ctrl-D'

my program has read in a large file of words (a dictionary) and inserted them all into a hash table. I am prompting the user to lookup a word and I want them to be able to terminate the program by pressing Ctrl-D. This is what I have tried but when I press Ctrl-D it just gets stuck in a loop printing out what I have in the else statement. I am using Unix. I have attempted looking this up on this website and nothing was working that I was trying hence why I am asking my own question. Any thoughts? PS. The transform is to make the user input all uppercase to match the file I am reading from.
void query(){
bool done = false;
string lookupWord;
while(!done){
cout << "Type a word to lookup or type ctrl-D to quit: ";
cin >> lookupWord;
if(atoi(lookupWord.c_str()) == EOF)
done = true;
else{
transform(lookupWord.begin(), lookupWord.end(), lookupWord.begin(), ::toupper);
cout << endl << "Word: " << lookupWord << endl;
cout << endl << "Definition: " << myDict.lookup(lookupWord) << endl << endl;
}
}
}
atoi(lookupWord.c_str()) == EOF
This doesn't do what you think it does. This checks the return value of atoi() and compares it to EOF. EOF is typically defined as -1. So, the code ends up setting done only when -1 is typed in. Which is not what you want.
std::istream has a convenient operator bool that tests whether the file stream is in a good state. So, all that really needs to be done is:
if (cin >> lookupWord)
{
// Your existing code is here
}
else
{
done=true;
}

Ignore Spaces Using getline in C++ [duplicate]

This question already has answers here:
Need help with getline() [duplicate]
(7 answers)
Closed 7 years ago.
Hey, I'm trying to write a program that will accept new tasks from people, add it to a stack, be able to display the task, be able to save that stack to a text file, and then read the text file. The issue comes when I am trying to accept input from the user, whenever you enter a string with a space in it, the menu to choose what to do just loops. I need a way to fix this. Any help would be greatly appreciated.
// basic file io operations
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
int main () {
//Declare the stack
stack<string> list;
//Begin the loop for the menu
string inputLine;
cout << "Welcome to the to-do list!" << endl;
//Trying to read the file
ifstream myfile ("to-do.txt");
if(myfile.is_open()){
//read every line of the to-do list and add it to the stack
while(myfile.good()){
getline(myfile,inputLine);
list.push(inputLine);
}
myfile.close();
cout << "File read successfully!" << endl;
} else {
cout << "There was no file to load... creating a blank stack." << endl;
}
int option;
//while we dont want to quit
while(true){
//display the options for the program
cout << endl << "What would you like to do?" << endl;
cout << "1. View the current tasks on the stack." << endl;
cout << "2. Remove the top task in the stack." << endl;
cout << "3. Add a new task to the stack." << endl;
cout << "4. Save the current task to a file." << endl;
cout << "5. Exit." << endl << endl;
//get the input from the user
cin >> option;
//use the option to do the necessary task
if(option < 6 && option > 0){
if(option == 1){
//create a buffer list to display all
stack<string> buff = list;
cout << endl;
//print out the stack
while(!buff.empty()){
cout << buff.top() << endl;
buff.pop();
}
}else if (option == 2){
list.pop();
}else if (option == 3){
//make a string to hold the input
string task;
cout << endl << "Enter the task that you would like to add:" << endl;
getline(cin, task); // THIS IS WHERE THE ISSUE COMES IN
cin.ignore();
//add the string
list.push(task);
cout << endl;
}else if (option == 4){
//write the stack to the file
stack<string> buff = list;
ofstream myfile ("to-do.txt");
if (myfile.is_open()){
while(!buff.empty()){
myfile << buff.top();
buff.pop();
if(!buff.empty()){
myfile << endl;
}
}
}
myfile.close();
}else{
cout << "Thank you! And Goodbye!" << endl;
break;
}
} else {
cout << "Enter a proper number!" << endl;
}
}
}
You have to add cin.ignore() right after options is chosen:
//get the input from the user
cin >> option;
cin.ignore();
And cin.ignore() is not necessary after your getline:
getline(cin, task); // THIS IS WHERE THE ISSUE COMES IN
//cin.ignore();
The problem is in options - if you didn't call cin.ignore() after it, options will contain end of line and loop will continue...
I hope this helps.
Don't do this:
while(myfile.good())
{
getline(myfile,inputLine);
list.push(inputLine);
}
The EOF flag is not set until you try and read past the EOF. The last full line read read up-to (bit not past) the EOF. So if you have have zero input left myfile.good() is true and the loop is enetered. You then try and read a line and it will fail but you still do the push.
The standard way of reading all the lines in a file is:
while(getline(myfile,inputLine))
{
list.push(inputLine);
}
This way the loop is only entered if the file contained data.
Your other problem seems to stem from the fact that you have:
std::getline(std::cin,task); // THIS is OK
std::cin.ignore(); // You are ignoring the next character the user inputs.
// This probably means the next command number.
// This means that the next read of a number will fail
// This means that std::cin will go into a bad state
// This means no more input is actually read.
So just drop the cin.ignore() line and everything will work.
Instead of using ">>" directly on your stream you might consider using getline and then attempting to fetch your option from that. Yes, it's less "efficient" but efficiency isn't generally an issue in such situations.
You see, the problem is that the user could enter something silly here. For example, they could enter something like "two", hit enter, and then your program is going to pitch a fit as it happily continues trying to decipher an empty option over and over and over and over again. The user's only recourse the way you have it set up (and the way those recommending use of ignore() are recommending) is to kill your program. A well behaved program doesn't respond in this way to bad input.
Thus your best option is not to write brittle code that can seriously break down with the most modest of user ignorance/malfunction, but to write code that can handle error conditions gracefully. You can't do that by hoping the user enters a number and then a newline. Invariably, someday, you'll bet poorly.
So, you have two options to read your option. First, read a full line from the user, make sure the stream is still good, and then turn the string you get into a stream and try to read your integer out of it, making sure this other stream is still good. Second option, attempt to read a number, verify that the stream is still good, read a line and make sure the stream is still good and that your string is empty (or just ignore it if it isn't, your choice).
#Vladimir is right. Here is the mechanism behind the bug:
When you enter option '3', what you actually put into stream is "3\n". cin >> option consumes "3" and leaves "\n". getline() consumes "\n" and your call to ignore() after getline() waits for user input.
As you can see, teh sequence of events is already not what you expected.
Now, while ignore() is waiting for input, you type in your line. That line you're typing is what will go to "cin >> option.
If you just give it one symbol, ignore() will dispose of it for you, and option will be read correctly. However, if you give it non-numeric symbols, stream will set failbit when trying to read the option. From that point on, your stream will refuse to do anything. Any << or getline will not set any new values in the variables they are supposed to change. You'll keep 3 in option and "" in task, in a tight loop.
Things to do:
always check cin.eof(), cin.fail() and cin.bad().
always initialize your variables and declare them in the narrowest scope possible (declare option=0 right before it's read).
I just figured out a way to kind of hack through it, not the greatest but it works. Create a character array, and then accept input in the array, and then put everything into the array into the string.
char buff[256];
cout << endl << "Enter the task that you would like to add:" << endl;
cin >> task;
task += " ";
cin.getline(buff, 256);
for(int i = 1; buff[i] != 0; i++){
task += buff[i];
}