Eclipse c++ twists code flow - c++

with the following code
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Insert number: " << endl; // prints "Insert number:"
cin >> num; //Reads num
cout << num; //prints num
system("PAUSE");
return 0;
}
i get the following result in the internal console of eclipse:
Insert number: //code in line 6
3 //code in line 7 (Input)
Press any button... //code in line 10
//empty line after pressing any button
3 //code in line 8?!?!?
And I have no idea why this is happening. It looks like eclipse just twists the execution of the code. But why and how could i solve this problem?

It's called buffering. Output to std::cout is buffered, and won't be displayed unless the buffer is flushed (which happens at program exit) or you explicitly flush it with the flush or endl standard I/O manipulators.
That the output of the PAUSE command is displayed is because it bypasses the std::cout buffering of your process, and either writes directly to the console window or because it flushes its own internal buffers (the PAUSE command will be run as an unrelated process, with its own possible buffering).

Related

Why does a cout statement at the beginning of my program not output anything?

So I'm working on some code for a class. Yes I know the input validation I'm trying to work out is inefficient and the program is unfinished. I don't need the rest of it to work. Here's the code.
/*Write a program that allows the user to enter a payroll code.
The program should search for the payroll code in the file and then display the appropriate salary.
If the payroll code is not in the file, the program should display an appropriate message.
Use a sentinel value to end the program.*/
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
int code;
ifstream PayrollFile;
int FCode;
int Salary;
char Trash;
string line;
string lineTwo;
int NumOfCodes=0;
int Subscript=0;
cout << "everything is starting";
PayrollFile.open("/Users/fnord/Desktop/Payroll.txt");
do{
lineTwo=line;
PayrollFile >> line;
NumOfCodes++;
}
while (line!=lineTwo);
PayrollFile.close();
PayrollFile.open("/Users/fnord/Desktop/Payroll.txt");
int ListOfPayrollCodes[NumOfCodes-1];
while (Subscript<NumOfCodes){
while (PayrollFile >> FCode >> Trash >> Salary) {
cout << FCode;
ListOfPayrollCodes[Subscript]=FCode;
Subscript++;
}
}
PayrollFile.close();
PayrollFile.open("/Users/fnord/Desktop/Payroll.txt");
cout << "please enter the payroll code";
cin >> code;
while (PayrollFile >> FCode >> Trash >> Salary) {
if (code==FCode) {
cout << "The salary is " << Salary << endl;
}
}
PayrollFile.close();
}
The thing I'm confused about is the fact that the compiler never seems to reach this line:
cout << "everything is starting";
As far as I can tell, there is nothing before this line that should stop the program from outputting "everything is starting" but "everything is starting" never shows up in the output.
The code builds and begins running but never stops and fails to output anything. My teacher couldn't figure this out either.
I'm running OSX10.9 and using XCode for my compiler. I've tried other compilers with the same results.
Thanks!
In these loops:
while (Subscript<NumOfCodes){
while (PayrollFile >> FCode >> Trash >> Salary) {
cout << FCode;
ListOfPayrollCodes[Subscript]=FCode;
Subscript++;
}
}
If extraction fails, PayrollFile starts converting to false, and there's no longer any way for Subscript to increase. So the outer loop never terminates.
Instead use:
while ((Subscript<NumOfCodes) && (PayrollFile >> FCode >> Trash >> Salary)) {
cout << FCode;
ListOfPayrollCodes[Subscript]=FCode;
Subscript++;
}
For your printf-debugging needs, when using cout, also use std::flush or std::endl. Otherwise the output will be buffered, and not help you learn where your program got stuck. (For actually writing out large quantities of data, you'll want to avoid flushing any more than necessary, because it kills performance.)
Use breakpoints. when you started to debug check if they are still red or turned white. if turned white you can see a note there about the situation. if its red and you cant reach it means its never getting there.
cout is a buffered stream; to force the output you should
using endl manipulator;
usinf flush() method
int ListOfPayrollCodes[NumOfCodes-1]; - // This line should not compile.You're using a variable to declare the size of an array . This is supposed to be a constant.
I'm not sure how you compile this code. Please fix a constant and see, how it sounds. I hardcoded it and commented the Numcodes increment line and I could print it.
Update: Ok, Looks like you're saying the compiler does not reach this line. That means, the code does not compile. The reason is above.
I understand that you want an array of size ListOfPayrollCodes. Use dynamic allocation as opposed to static allocation, it will work fine.

getline c++ problems with pipe overflow (?)

I have made a simple program in c++ to read out a file
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text;
getline(cin, text);
int textlength = 0;
textlength = text.length();
cout << text << endl;
cout << text[3] << endl;
cout << textlength << endl;
int number=0;
cout << "Enter a number: " << endl;
cin >> number;
}
So I compile this program in Win 8.1 pro + mingw and everything is okay. Next I start it by writing in cmd a.exe < sample.txt. The compiled program and the txt must be in the same folder.
sample.txt is a file with that text (some random letters, numbers etc.):
iuhuefusifsduifhsdiufhfdliuhfdslhfdiufhfdslihfsdui 6 rer4 r4 r4t 4t46 t 4t43t 00 00 002 " & %
Everything works fine until the point with the last cin. I cannot enter a number at that point because the entering process is skipped. I also tried to read out the text without the getline function. Instead I simply repeated a cin process and saved the progress one by one in a char. Worked fine until the cin command at the very end. It skipped that yet again.
And ideas how to solve that problem?
At that point, cin is still reading from your file sample.txt - and failing to read a number, because the getline has already read all the contents of the file.
Adding a second line to sample.txt would let you read a number (but beware that the error handling can get quite tricky if the input is not a number).

Using code from standard library to stop output from exiting in Turbo C++

Many of folks here are telling me to stop using clrscr(), getch() etc. and I have started learning C++ with the standard library and now that I want to follow the standard library how would I stop the output from immediate exit after run?
include <iostream.h>
include <conio.h> // Instead of using this
void main(){
cout << "Hello World!" << endl;
getch(); // Instead of using this
}
You can directly run the binary from command line. In that case after the program is finished executing the output will still be in the terminal and you can see it.
Else if you are using an IDE which closes the terminal as soon as the execution is complete, you can use any blocking operation. The simplest is scanf (" %c", &dummy); or cin >> dummy; or even getchar (); and what Adriano has suggested. Although you need to press Enter key, as these are buffered input operations.
Just replace getch() with cin.get() like this:
include <iostream>
using namespace std;
void main()
{
cout << "Hello World!" << endl;
cin.get();
}
For more details see get() function documentation. Just for reference you may do this, for example, to wait until user pressed a specific character:
void main()
{
cout << "Hello World!" << endl;
cout << "Press Q to quit." << endl;
cin.ignore(numeric_limits<streamsize>::max(), 'Q');
}

C++ code to automatically close console

I am currently learning C++ for a programming course. I noticed that my professor's program automatically closes at the end of their program. It usually prompts the user for an input, and then upon entering an input, the program closes. How would I code that? I only know using return 0 gets me "Press Any Key to Continue"
Note: this is a .exe file
If your program doesn't wait for any input, it runs and finally exits from the program. On exiting, the console automatically closes. I assume, to run the program you're clicking on the .exe, as opposed to runnng the program from cmd.exe, or you run the program from visual studio itself without debugging.
You could just put the following line before return 0;:
std::cin.get();
It will wait for some input and then proceed.
use getch(); before return; statement
Return 0 to give "press any jey to continue" is debugger-specific behavior. Running your compiled exe outside the debugger usually wont show that.
The simple code below does a little more than you're asking for (it repeats what you typed in) but still gives the general idea.
#include <iostream>
using namespace std;
int main() {
cout << "enter something" << endl;
string stuff;
cin >> stuff;
cout << "You entered " << stuff << " you insensitive clod" << endl;
return 0;
}
it is easy, at the end of your main() function put this:
int x;
cin >> x;
this define a new variable and tries to fill it with user-input and then the program will not be terminated till the user gives it input. This is how the program reaches the Press any key to continue, finally you exit the program with a 0 argument and the console window will be destroyed automatically since it is the main window of the process.
I recommend to use:
std::cin.clear();
std::cin.sync();
std::cin.get();
cause there may be times when you need to write something and you will need to press ENTER which will make
std::cin.get();
useles. As it will remeber the first time you pressed ENTER and close the window.
Sample:
#include <iostream>
#include <string>
int main()
{
std::string name;
std::cout << "Your name: ";
std::cin >> name; \\ <--Place where you press ENTER <--------------
std::cout << "Hi, " << name << ".";
std::cin.get();
return 0;
}

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];
}