I've searched around here first, and seen many solutions to making Visual C++ hold the console open at the end of program's execution, but I'm getting some weird behavior from one of the methods, and I don't understand where this behavior is coming from.
So (a) what's the best method (besides crtl-F5 and setting subsystem to console) to hold the console open?
and (b) why am I getting the strange behavior that I will now elaborate on?
Here is the code
/*
Learning how about variables and accepting inputs
*/
#include <iostream>
using namespace std; // cout and cin from the standard namespace.
// using std::cout; -- alterative declarations
// using std::cin;
int main()
{
char first, last;
cout << "Please enter your first and last names:\n";
cin >> first; // get one char
cin.ignore(256,' ');
cin >> last; // get one char
cout << "Your first and last initials are " << first << last;
cin.ignore('\n');
return 0;
}
The strange behavior is, I have to press the Enter exactly 4 times before it will exit the console.
Why 4 times?
Related
this is some code that i have in C++:
#include <iostream>
using namespace std;
int main() {
int num1;
string some;
cout << "enter something";
cin >> num1 >> some;
cout << num1 << endl << some;
return 0;
}
I'm a bit confused about how inputting works exactly in C++. First of all, through observation i figured that when asking for multiple inputs, C++ looks for either space or line separated data and am not sure if that is exactly true as websites i have looked at don't say this explicitly. Also my main problem is what happens when for num1, which is an integer variable, i input 'hello', which is a string, and click enter. In that case, C++ doesn't even ask me for an input for some and instead just outputs 0. I am a beginner in C++ and am very confused why this happens as i would expect an error message instead. I am hoping that someone would explain to me the procedure that C++ goes through when dealing with a situation like this, where a string gets stored in an int variable, to better understand inputting in C++. Thanks!
With "Hello" you are putting the cout and cin into an error state where especially cin doesn't accept any further input.
If you want to prevent the user from writing text instead of numbers, you have to check each input character. There are several functions that can check if a key code equals a number or not.
During debugging Eclipse doesn't "see" INPUT from built-in console, just ignores it. Simple example:
#include <iostream>
using namespace std;
int main() {
int a;
cin >> a;
cout << a << endl;
cin >> a;
cout << a << endl;
return 0;
}
works perfectly fine when just run, but when I try to debug it, first "data on input"(?) is always a number around 40, and only zeros next, no matter what i will write to console.
So program executes, first variable is set to ~40 and all next to zeros.
Output works fine, values are written to console, only input doesn't work.
I work on Windows 10 and use MinGW.
Thanks in advance.
#EDIT
Everything works, when I use native Windows console
(.gdbinit file with set new-console on line)
I am a bit ashamed with this, but really I can't see what's not working properly with this code. For now it should only store some book names (hence the array and the getline()), and the first cin indicates how many of them I am going to store. But I don't know why, if I enter a number N for nbBooks, I am only able to enter N-1 book names, and library[0] (last book entered) is just a space.
#include <iostream>
using namespace std;
int main()
{
int nbBooks;
cin >> nbBooks;
string library[nbBooks];
while(nbBooks--) {
getline(cin, library[nbBooks]);
}
cout << library[0];
return 0;
}
I know there must be something with getline(), but even though I did search answers about this I couldn't find any.
arrays must has a Specific size at compile time not at runtime.
this code will issue an error flag: "error C2133: 'library' : unknown size"
if you want to allocate an array with a size assigned at runtime then:
use the memory HEAP:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int nbBooks;
cout << "nBooks: ";
cin >> nbBooks; // nBooks is not defined until runtime
cout << endl;
cin.sync(); // flushing the input buffer
string* library = new string [nbBooks]; // allocating pointer to array on the heap memory not the stack
int i = 0;
while(nbBooks--)
{
cout << "library[" << i << "]: ";
getline(cin, library[i]);
i++;
cin.sync(); // flushing again the buffer remeber "safe programming is the purpose of any programmer"
}
cout << "library[0]: " << library[0] << endl;
// now remember memory of heap is not unallocated by the compiler so it must be fred by the programmer
delete[]library; //dont forget "[]"
return 0;
}
now compile the code and everything will work correctly.
I use cin.sync() right after cin>> nbooks; to ensure FLUSHING the input buffer.
and once again inside the loop after any assignment to the elements I used another to ensure flushing the buffer.
as I know there's an error in getline which doesn't flush the input buffer totally so some data will affect other variable, to overcome this problem we use cin.sync() to ensure emptying the buffer.
Alright, I am a bit confused : a simple cin.ignore() before the getline() function made it work now, while the same thing wasn't working 10 minutes ago (eventhough I was rebuilding and recompiling each time)(and I swear to god I am not idiot enough to forget that ;) )... So sorry for my pretty useless question...
Oh by the way :
while(nbBooks--) {...}
It evaluates the value nbBooks, then decrement it, so no problem here.
Well, the problem is with the \n character which is staying in the buffer after this cin >> nbBooks; line gets executed. The operatot>> method of cin does not accept \n by default thus the newline character is not pulled out from the buffer. So, you have to pull it out, right?. Just add cin.get(); after cin >> nbBooks;. The get() method will extract the \n character. Rest of the code is fine.
Here is an example code demonstrating the problem I'm facing.
#include <iostream>
#include <string>
extern "C" {
#include <unistd.h>
}
int main()
{
std::cout << "Making tests ready!" << std::endl;
std::cout << "\nTo start out, Enter an integer: ";
int a = 0;
std::cin >> a;
std::string input;
sleep(3); // what to do if user enters data during this?
std::cout << "\n Now enter a string";
std::getline(std::cin, input);
std::cout << "\nHere are your values - " << a << " & " << input;
return 0;
}
See the sleep call in between the code? This could be replaced with somewhat long delays while computing something when my program isn't accepting any inputs. Now if user presses some keys during this time, that input is captured by std::getline() in next line of code. I know this is the default behavior since it should capture the input being provided.
But what I want is to clear all that captured input and start fresh with 15th line that is std::cout << "\n Now enter a string";, which is immediately after sleep. I don't know exact term to describe this or else I would have used that. Thanking you.
Edit: I've tried using std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); in my code, but it asks for input and then discards it.
Please mind my english, not a native speaker.
Reading the comments causes me to think that you can't really solve this problem (at least by the means suggested there). There's an inherent race condition in any case. Consider the following lines:
sleep(3);
// (*) <- Potential location 1.
std::cout << "\n Now enter a string";
// (**) <- Potential location 2.
std::getline(std::cin, input);
The various comments show some (very technically-competent) ways to flush the standard input. The problem is, you cannot put them in the location marked (*) nor (**).
First location - you clear the standard input some way. Now you decide it's time to move to the next line (std::cout << ...). While you do that, the user types in some more input. Race!
Second location - You print out the message (std::cout << ...), and proceed to clear the standard input. Before you manage to do that, the user typed in something. Race!
It seems to me that any of the techniques described in the comment require locking the standard input, and I don't think there's a (standard) way to do so.
I use Visual C++ 2010 Express Edition to compile and run the .exe files I write in the C++ programming language. I am trying to create a loop-based logic using C++ to ask the user how many entries he chooses to enter, and ask questions limited to that no. of entries. For example I want to output, "How many characters do you wish to enter?: " Say the user gives the answer as '3' which is stored in the int variable 'entries'. I then want to keep asking the question 3 times before it stops and continues with the next line of code. I hope you understand, here is a block of code to demonstrate what I am doing:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "How many values do you need to enter?: ";
int entries;
cin >> entries;
int offset, number;
string valueName[50];
float valueValue[50];
for (offset = 0; offset < entries; offset++)
{
cout << "Enter " << number << " Value Name: ";
cin >> valueName[offset];
cout << "Enter " << valueName[offset] << "\'s value: ";
cin >> valueValue[offset];
for (number = 1; number <= entries; number++)
{
}
}
char response;
cin >> response;
return 0;
}
Strangely when I run this simple program, it fails when I enter the value's name to be inserted into the 0th element of the valueName[] array. It just pauses the execution of the program and a dialog box pops up saying "Runtime Check Failure #3 - Variable 'number' is being used without being initialized!" Another problem regarding this program is that, for quite some time, when I ran this program this "Runtime Check Failure #3" box never appeared, and when it didn't, the number value went wrong, and first started with 1, and then for the next loop jumped to 6, and then repeated 6 again for the next loop! Please help me! I've checked online scouring this problem everywhere, but it just doesn't apply to my type of problem! Is it because the variables are out of scope? But they're declared outside the for loops right? So please help me!
The runtime is telling you the truth, the following line comes after you have declared number as an int but have not given it a value.
cout << "Enter " << number << " Value Name: ";
In your code you declare the following, in C++ this means give me 2 ints but the values are not defined yet, e.g.
int offset, number;
Change it to something like this ..
int offset = 0;
int number = 0;
You are printing the variable number without assigning to it first, i.e. it's uninitialized. When it prints some random number it's because that what happens to be in the memory at the time you run the program. Assign a value to it before you use it.
The problem is exactly the error message you're getting. You're using the variable number without initializing it.
You use the variable right here, at the top of your loop, when it hasn't been initialized to anything yet:
cout << "Enter " << number << " Value Name: ";
What is your intention with the number variable? It doesn't really seem to be serving any purpose. If you want to print which entry you're currently on, you could use the offset variable instead, like this:
cout << "Enter " << offset << " Value Name: ";
But that still seems a little unclear to me.
But the reason that you're having a problem is because the value is uninitialized, so you're experiencing undefined behavior. This is also the reason that Visual Studio doesn't always catch it; it will probably always catch in Debug mode, but in Release mode it will almost never catch it. You need to initialize all your variables before you use them.
In my case it was because an extern variable was declared twice.