std::cin is not accepting input - c++

I am trying to get the first program working from "Accelerated C++".
I was having trouble getting the program to stay open without shutting down, so I decided to put a int i = 0; and cin >> i; after main() returns. Unfortuantely, it doesn't seem to take any input, no matter where I put that cin statement.
If it helps, it is using an istream reference to accept cin input. I can't figure out how to enter code on this site.

For most of my adult life, I used system("PAUSE") without any problems to keep the program window open. It's not good for real-time systems, of course, but it's simple and powerful because you're actually running a console command and it can be used to make console scripts.
#include <iostream>
#include <cstdlib>
using namespace std;
inline void Pause () { cout << "\n"; system ("PAUSE); }
int main () { Pause (); }
This solution is not 100% portable, but it will work on PCs. A more portable solution is:
#include <conio.h>
#include <cstdio>
void Pause() {
cout << "\nPress any key to continue...";
while (_getch() < 0)
;
}
cin is good for doing simple things, but what I do is wrap the std library in C functions and use those because it can dramatically improve compile times to hide the std library headers in the implementation files.
The prefered method in C++ is std::getline() using std::string, though many teachers won't let you use that.
With cin, you also have to clear input errors and use ignore() to throw away a specific number of chars.
#include <string>
string foo;
cout << "Why do they always use foo? ";
getline (cin, foo);
cout << "You just entered" << foo;
int bar;
cout << "\nThe answer is because programmers like to go to the bar."
"\nHow many times have you seen foo bar in an example? ";
while (!(cin >> bar)) {
cout << "\nPlease enter a valid number: ";
cin.clear ();
cin.ignore (10000, '\n');
}
My many years of experience have taught me to put the \n char at the beginning of output lines as opposed to the end of them.

Related

Creating a first C++ project in Visual Studio [duplicate]

This question already has answers here:
How to keep the console window open in Visual C++?
(23 answers)
Closed 4 years ago.
My IDE is Visual Studio 2017.
I am pretty new in C++ programming so I need a help about understanding principles of creating a new C++ project in Visual Studio.
So, in my first solo attempt i just chose a empty project option and afther that i chose to add new item and i write this sample code:
#include <iostream>
using namespace std;
int main()
{
return 0;
}
Afther this step and afther steps with compiling, building and a starting without debugging i did not get any message or consol window with time of code execution or option for entering any key for ending.
What is needed for getting this kind of information at the end of code?
You shouldn't use system("pause"); you can read here why. It's platform dependent and adds a huge overhead loading all the Windows specific intstructions.
So you should choose nicer alternatives: std::cin.get() for example. Which will work most of the time. Well, except if there had been input before (std::getline or std::cin). If you're creating a program with user input - use std::cin.ignore() twice to guarantee a "press enter to continue" effect:
#include <iostream>
int main() {
int a;
std::cin >> a;
std::cin >> a;
std::cin >> a; //etc
std::cout << "press enter to exit - - - ";
std::cin.ignore(10000, '\n');
std::cin.ignore(10000, '\n');
return 0;
}
also please don't use namespace std; read here why.
If you don't like this 3-liner (because it looks ugly) you can pack it in a void function and treat the whole thing as a black box:
void pause() {
std::cout << "press enter to exit - - - ";
std::cin.ignore(10000, '\n');
std::cin.ignore(10000, '\n');
}
int main(){
pause();
return 0;
}
Converting Blaze's comment to an answer
Go to Tools->Options->Debugging and look for an option called "Automatically close the console when debugging stops" and ensure that this option is not activated.
I did not get any message or consol window with time of code execution or option for entering any key for ending
Because you didn't ask for it.
What is needed for getting this kind of information at the end of code?
To perform input (see std::cin and operator<<) and output (see std::cout and operator>>). Example:
#include <iostream>
int main()
{
std::cout << "Press enter to terminate\n";
std::cin.get();
}

C++ function to check if an input is an integer?

I'm currently writing a C++ program for school that involves taking an input as an amount of change, then telling the user how many quarters, dimes, nickels, and pennies they require to make said change.
However, if the user inputs any sort of character or string the program goes into an infinite loop printing two or three of my messages indefinitely.
Is there a function or some other method I can use to prevent this from happening?
Edit: Here's some of my code that I think represents the issue
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cctype>
#include <sstream>
using namespace std;
int main ()
{
cout << "\nMake Change v0.6.4\n";
cout << "Type 0 at any time to exit the program.\n";
char confirmExit;
int amount;
while (tolower(confirmExit) != 'y')
// allows the user to continue using the program with having to type a.out everytime
// but quit the application at any time with two keystrokes and
// confirmation so as to not accidentally exit the program
{
cout << "\nEnter the amount of change as an integer: ";
// input total cents to be worked with
cin >> amount;
if ((amount)!int)
{
cout << "\nMake sure to type an integer!\n";
}
else if (amount == 0)
{
cout << "Are you sure you want to exit the program(y/n)? ";
cin >> confirmExit;
// confirmation to prevent accidentally exiting out
}
cout << "\n";
return (0);
}
In C++ everything is bits and implicit conversion can takes place to convert string or other forms of data to int value. You can use limits header file in standard library and set the bound for max and min value of input.If you can't get it then comment below. I will post code.
This link might be useful-
Visit http://lolengine.net/blog/2012/02/08/selectively-restrict-implicit-conversions
see the functions defined below:
atoi
strtol

Control stdin and stdout of second program (pipes/piping?)

I've been wondering how to go about running a program within another program where the the main process can output into the stdin of the secondary process as well as have that second process output to the input to the primary one.
The closest I have come to finding a term for this idea is pipes and forks but I don't quite get the examples i've seen. I've only seen ones where the same program is using pipes to launch itself again. Additionally all of these examples assume that that the programmer is writing/has access to both program's source code.
I would like to be able to interface in this way with programs that are already compiled. Here's an example of what I would like to be able to do:
This is the "compiled" program-
#include <iostream>;
using namespace std;
int main(){
int answer = 42;
int guess = 0;
do{
cout << "Guess a number..." << endl;
cin >> guess;
if(guess<answer)
cout << "Guess Higher!" << endl;
else if(guess>answer)
cout << "Guess Lower!" << endl;
}while(answer!=guess);
cout << "You win!";
return 0;
}
This is the "parent" program-
#include <iostream>;
using namespace std;
int main(){
//Code executing and connecting the other program
//while cin/cout would be nice for keeping it clean, other methods of doing this are fine
//I used cin/cout as placeholders to try and make what I am asking clearer
String out;
cin >> out;//Load initial prompt
int high=100, low=0;
do{
cout << (high+mid)/2 << endl;
cin >> out;//Load response
if(out.compare("Guess Higher!"))
low = (high+low)/2;
else
high = (high+low)/2;
}while(out.compare("You win!")!=0);
return 0;
}
The idea here is that my "parent" program could play this game for me. It would make a guess, view the response, use some logic to decide what to do next, guess, repeat until it wins. This particular example is pretty useless but the same general idea of controlling one program with another has a lot of uses. This is just a hypothetical demo of would I would like to be able to do.
Thanks to anyone kind enough to take time out of their day to help.

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.

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');
}