c++ fstream only outputting one case - c++

void budgetCheck() {
for (int i = 0; i != 100; i++) {
if (arrayTotalCost[i][2] > arrayTotalCost[i][0]) {
outputValidPackage(i);
}
else outputInvalidPackage(i);
}
}
void outputValidPackage(int i) {
fstream validPackage;
if (validFirst = false) {
validPackage.open("requestOutValid.txt");
validFirst == true;
}
validPackage << "Total cost is : " << arrayTotalCost[i][0] << " , the budget is : " << arrayTotalCost[i][2] << endl;
validPackage << "The Sydney to Tokyo flight is on day " << flightTicketArray[i][1] << " and costs " << flightTicketArray[i][3] << endl;
validPackage << "The Tokyo to Sydney flight is on day " << flightTicketArray[i][2] << " and costs " << flightTicketArray[i][4] << endl;
validPackage << "A " << hotelArray[i][3] << " star hotel, from day " << hotelArray[i][1] << " to " << hotelArray[i][2] << " will cost " << hotelArray[i][4] << endl;
}
void outputInvalidPackage(int i) {
fstream invalidPackage;
if (invalidFirst == false) {
invalidPackage.open("requestOutInvalid.txt");
invalidFirst = true;
}
invalidPackage << "Package is invalid" << endl << endl;
}
The goal of the code is to take in requests from a text file, and then output the valid and invalid requests into separate text files.
Everything else in the code is working.
I would expect 100 cases between the two text files. But only one is outputting. I am not sure why, the outputted case is seemingly random but the same one every time. The 92nd case. It is not the last valid package or the first invalid. Though it is a valid case.
EDIT : changed = to == . Now one case is printed to both files.

Related

Advise needed to make a good nested else/if statement in function

I'm currently building a function that has to do with a pharmacist's input and I was wondering if this was the proper way to construct it using else/if statements. Am I lacking in some parts? (I've been getting this one single "expected declaration of the '}'" error that's been driving me crazy and have been trying to fix it for the past hour or so but to no avail.)
I would love to hear your advice on the parts that I might be missing out.
I've also listed the location of the error in the code below.
Thank you so much!
void pharm_page()
{
int choice3;
char pharm_user[30];
char pharm_pass[30];
char ship, ship_choice;
bool value_found = true;
system ("pause");
cout << "\n --------Pharmacist Login-------";
cout << "\n\n Please enter your username: ";
cin >> pharm_user;
cout << "\n Please enter your password:";
cin >> pharm_pass;
if ((strcmp (pharm_user, USER1) == 0) &&
(strcmp (pharm_pass, USER1PASSWORD) == 0))
{
getchar();
system("pause");
cout << "\n";
cout << "Success! You will be redirected to the pharmacist page." << endl;
cout << "\n";
cout << "------------------ Pharmacist Page -----------------\n" << endl
<< "Press 1: Access Patient Records" << endl;
cin >> choice3;
if (choice3 == 1)
{
const int ship_WM = 8.00;
const int ship_EM = 12.00;
int patient_id;
bool value_found = true;
cout << "-------------- Enter patient ID : ";
cin >> patient_id;
cin.ignore();
for (int i = 0; i < SIZE_P; i++)
{
if (patient_id == pat[i].p_id)
{
cout << "Patient Name : " << pat[i].p_name << endl
<< "Patient ID : " << pat[i].p_id << endl
<< "Doctor Name : " << pat[i].p_doctor << endl
<< "Appointment Date : " << pat[i].p_date << endl
<< "Medicine Expiry Date : " << pat[i].expiry << endl
<< "Medicine Name : " << pat[i].med_name << endl
<< "Medicine Quantity : " << pat[i].med_q << endl
<< "Direction of Use : " << pat[i].direct << endl
<< "Patient's Address: " << pat[i].p_add << endl
<< "Continue prescription? " << pat[i].option << endl
<< "\n" << endl;
cout << "\t\t========================================================================================\n\n";
cout << "\t\tPlease take note that fridge items e.g. insulin, medication in liquid form e.g. syrup or \n";
cout << "\t\tlotion and pressurized canisters e.g. inhalers are not eligible for postage. Kindly \n";
cout << "\t\t\t\t\tsource at the nearest hospital/pharmacy.\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n";
cout << "\t\t========================================================================================\n\n";
cout << "--------- State the method of pick-up for patient's medicine (Press A for 'Shipping' or B for 'Pick-up'): ";
cin >> ship;
if (toupper(ship) == 'A')
{
cout << "You have chosen to ship the medicine. Please enter the shipping zone of the patient to determine shipping charges. (EG: Press C for 'WM' or D for 'EM'): " << endl;
cin >> ship_choice;
if (toupper(ship_choice) == 'C')
{
for (int i = 0; i < 1; i++)
{
ofstream file_label("patient.txt");
if(file_label.is_open())
{
file_label << "Patient Name : " << pat[i].p_name << endl;
file_label << "Patient ID : " << pat[i].p_id << endl;
file_label << "Doctor Name : " << pat[i].p_doctor << endl;
file_label << "Appointment Date : " << pat[i].p_date << endl;
file_label << "Medicine Expiry Date : " << pat[i].expiry << endl;
file_label << "Medicine Name : " << pat[i].med_name << endl;
file_label << "Medicine Quantity : " << pat[i].med_q << endl;
file_label << "Direction of Use : " << pat[i].direct << endl;
file_label << "The medicine will be shipped to the patient's address at " << pat[i].p_add << "." << endl;
file_label << "Shipping charges: RM" << ship_WM << endl;
file_label.close();
cout << "\n" << endl;
break;
}
}
}
else if (toupper(ship_choice) == 'D')
{
for (int i = 0; i < 1; i++)
{
ofstream file_label("patient.txt");
if(file_label.is_open())
{
file_label << "Patient Name : " << pat[i].p_name << endl;
file_label << "Patient ID : " << pat[i].p_id << endl;
file_label << "Doctor Name : " << pat[i].p_doctor << endl;
file_label << "Appointment Date : " << pat[i].p_date << endl;
file_label << "Medicine Expiry Date : " << pat[i].expiry << endl;
file_label << "Medicine Name : " << pat[i].med_name << endl;
file_label << "Medicine Quantity : " << pat[i].med_q << endl;
file_label << "Direction of Use : " << pat[i].direct << endl;
file_label << "The medicine will be shipped to the patient's address at " << pat[i].p_add << "." << endl;
file_label << "Shipping charges: " << ship_EM << endl;
file_label.close();
cout << "\n" << endl;
break;
}
}
}
else
cout << "Unable to open file. Please try again once the program restarts.";
}
}
else if (toupper(ship) == 'B')
{
for (int i = 0; i < 1; i++)
{
ofstream file_label("patient.txt");
if(file_label.is_open())
{
file_label << "Patient Name : " << pat[i].p_name << endl;
file_label << "Patient ID : " << pat[i].p_id << endl;
file_label << "Doctor Name : " << pat[i].p_doctor << endl;
file_label << "Appointment Date : " << pat[i].p_date << endl;
file_label << "Medicine Expiry Date : " << pat[i].expiry << endl;
file_label << "Medicine Name : " << pat[i].med_name << endl;
file_label << "Medicine Quantity : " << pat[i].med_q << endl;
file_label << "Direction of Use : " << pat[i].direct << endl;
file_label << "The medicine will be shipped to the patient's address at " << pat[i].p_add << "." << endl;
file_label << "Shipping charges: None " << endl;
file_label.close();
cout << "\n" << endl;
break;
}
}
}
}
}
else
value_found = false;
}
if(value_found)
cout << "No record of patient in database. Please re-enter current patient's number and try again. ";
else
cout << "Wrong input. Please try again." << endl;
}
} <============================================================== (that one error is located here)
else
{
cout << "\n";
cout << "Your credentials are wrong. Please enter the right credentials once the program has been terminated." << endl;
}
}
}
A good base line is that if you have a function that is long enough for you not to see it in one page, you should generate sub-functions.
Another good base line is that if you can easily name a sub-segment of your code, you should consider making it another function.
If you see that you repeat nearly similar code several times, like your writing lines, it's time to refactor. Avoid repeating the same code all over.
Most important: C++ is an OOP language. Use it as one.
For example, take your lines
cout << "Patient Name : " << pat[i].p_name << endl
<< "Patient ID : " << pat[i].p_id << endl
<< "Doctor Name : " << pat[i].p_doctor << endl
<< "Appointment Date : " << pat[i].p_date << endl
<< "Medicine Expiry Date : " << pat[i].expiry << endl
<< "Medicine Name : " << pat[i].med_name << endl
<< "Medicine Quantity : " << pat[i].med_q << endl
<< "Direction of Use : " << pat[i].direct << endl
<< "Patient's Address: " << pat[i].p_add << endl
<< "Continue prescription? " << pat[i].option << endl
<< "\n" << endl;
I'm not sure what pat stores, but given that it has members, it's at least a structure. Now why does that structure or class not have a method like print() or to_string()? Which would reduce your lines above to
cout << path[i].to_string() << endl;
Do similar things in other parts where you print a lot of things and your code should be far better to read already. Note that a to_string() method suits well as that would also work with your ofstream.
Question, is that what you show us a function or a method? It should be the latter. You should have something like a class PharmacyInterface which has such functionality as methods. Basically every single access you can name should be a method. Something like accessing the data of a single patient should be a method. Entering the password (and storing a boolean that it was successfully entered) should be a method. All those methods should read very shortly and straight-forwarded.
Basically, for anything that you nest, ask yourself if you can easily name it. If so, make it it's own method.
As for your error, use a proper IDE. If you use auto-indentation, the line with the missing { or } will stick out, and maybe even be marked as bad. Also, you can check to which opening brace a closing brace belongs by clicking behind it, a good IDE will then indicate the opening brace.
But in general, if you have troubles finding an incorrect bracing, your code is simply too convoluted, and you should use what I wrote above.
Lastly, I strongly recommend that you put your code on CodeReview, another StackExchange website which concerns itself with coding style rather than fixing bugs like StackOverflow does.
Note that the code you post there will be ripped apart, and that is quite useful for you to learn things.
Edit: Another thing I noticed is that you have a for loop that searches for an ID. This creates an avoidable nesting. Instead, have another method (or function if you want to go procedural) called size_t patient_index_from_id(int id) or similar, which does the search. Saves you from one nesting and can be reused.

sleep or time delay for C++ Program

So I'm writing this spinoff game of Paperboy as a class project. If I wanted to I could say I'm finished and turn it in but I want it to have a professional touch to it. My game consists of different modes: easy and hard. However I have not implemented the hard mode yet.
Anyway, here is my code
void easyMode() {
string playerName;
int numNewspapers, numDelivered = 0, numMissed = 0, score = 0;
cout << "Enter Your Player Name: ";
cin >> playerName;
cout << "\nEnter How Many Newspapers That Need To Be Delivered: ";
cin >> numNewspapers;
cout << "\n\nYou have " << numNewspapers << " newspapers to deliver!\n\n";
cout << "Time To Deliver !!\n\n";
cout << "*===================================*\n\n";
//cout << string(50, '\n');
while (numDelivered < numNewspapers) {
int outcome = RandomNumberEasy();
cout << "*===================================*\n\n";
cout << "Delivering Newspaper...\n\n";
// Game Sequence
//*===================================*
// Delivered Successfully
//*===================================*
if (outcome <= 3 || outcome > 7) {
cout << "You Successfully Delivered The Newspaper.\n\n";
numDelivered++;
score = score + 15;
cout << "Your score is " << score << " points!\n\n";
}
// Delivery Failed
//*===================================*
else {
cout << "The Neighbor's Dog Chased You. Delivered Paper Didn't Quite Land On Step\n\n";
numDelivered++;
numMissed++;
score = score + 5;
cout << "Your score is " << score << " points!\n";
}
cout << "\n";
sleep(1);
}
// END GAME
//*===================================*
if (numDelivered == numNewspapers) {
int SuccDeliver = numDelivered - numMissed;
cout << "*===================================*\n\n";
cout << "Congratulations, " << playerName << "!\n\n";
cout << "Your Final Score Is: " << score;
cout << "\n\nYou missed " << numMissed << " Newspapers And Delivered " << SuccDeliver << " Newspapers\n\n";
}
}
As you can see I do have the sleep function in there, but when I run my program, it waits a long time and the outputs every iteration all at once. I want it to wait in between each iteration but I can't seem to get it to work.
Any help is appreciated!
The problem seems to be that the output buffer is not being flushed. A way to do it is to use cout << endl instead of cout << "\n". Mainly, this part:
cout << "\n";
sleep(1);
Should be like this:
cout << endl;
sleep(1);
And that should fix it!

C++ - Assigning character values to a string in a vector using range based for loop doesn't assign the value

I'm working on a self-imposed practice exercise. The parameters are that I allow the user to enter a name that is stored in a vector. Printing the list of names in the vector gives you the position of each name. You can choose to encrypt a name in the list by providing the name's position. Encryption compares each letter in the name with another string that is the allowed alphabet for names. When it finds the letter in the alphabet, it pulls a corresponding character from another string of random characters and assigns the new character to the same position.
Using a range based for loop I almost got it to work. By adding output statements I can see the code correctly comparing the characters of a name to the allowed alphabet and finding the corresponding value in the encryption key. However when the loop is complete and I print the list of names again, the characters in the name to be encrypted are unchanged.
Trying to troubleshoot the issue, I have commented out the range based for loop and tried to do the same thing with a traditional for loop. With this code I get and error during encryption:
Position 1 A is the same as #
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 26) >= this->size() (which is 2)
The "Position 1 A is the same as #" line is a debug output that I added to show that the code is able to find the correct string, a letter in the string, and the corresponding letter in they key.
Any help in understanding why I get those errors would be appreciated.
Here's my code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
// Declare strings for Encryption and Decryption
string alphabet {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "};
string key {"mnbvfghytcqwi1234567890`~!##$%^&*()-=_+[]\{}|;':,./<>?"};
//Declare collection of names for the list
vector <string> names {};
//Declare character to hold the user menu selection
char selection {};
string user_input{};
string banner (50, '=');
//Print menu
do
{
cout << "\n" << banner << endl;
cout << "A - Add name to list" << endl;
cout << "P - Print all names in list" << endl;
cout << "E - Encrypt a name in the list" << endl;
cout << "D - Decrypt a name in the list" << endl;
cout << "S - Show details of a name in the list" << endl;
cout << "C - Clear all names in the list" << endl;
cout << "Q - Quit" << endl;
cout << banner << endl;
cout << "Selection: ";
getline(cin, user_input);
if (user_input.size() != 1)
{
cout << "Error 4: Menu selection must be a single character" << endl;
selection = '1';
}
else
{
for (auto c: user_input)
{
if (!isalpha(c))
{
cout << "Error 5: Menu selection must be an alphabetic character" << endl;
selection = '1';
}
else
selection = c;
}
}
// cin >> selection;
// cin.clear();
// cin.sync();
switch (selection)
{
case 'a':
case 'A':
{
string temp_name{};
bool invalid_name {false};
cout << "Enter full name: ";
getline(cin, temp_name);
if (!isalpha(temp_name[0]))
cout << "Error 2: Names must begin with an alphabetic character" << endl << endl;
else
{
for (auto c: temp_name)
{
if (!isalpha(c) && !isspace(c) && c != '-')
{
invalid_name = true;
break;
}
else
invalid_name = false;
}
if (invalid_name)
cout << "Error 3: Name contains invalid characters" << endl << endl;
else
{
temp_name.at(0) = toupper (temp_name.at(0));
for (size_t i {1}; i < temp_name.size(); i++)
{
size_t position{i-1};
if (isspace(temp_name.at(position)) || temp_name.at(position) == '-')
{
temp_name.at(i) = toupper(temp_name.at(i));
}
}
names.push_back(temp_name);
cout << "Added name #" << names.size() << endl;
}
}
break;
}
case 'p':
case 'P':
{
for (size_t i {0}; i < names.size(); i++)
cout << i+1 << ". " << names.at(i) << endl;
break;
}
case 'e':
case 'E':
{
size_t encrypt_input{}, key_position{}, name_position {}, name_size {};
cout << "Enter the position of the name to encrypt: ";
cin >> encrypt_input;
cin.clear();
cin.sync();
if (encrypt_input < 1 || encrypt_input > names.size())
cout << "Error 6: Invalid selection for name to encrypt" << endl << endl;
else
{
name_position = encrypt_input - 1;
name_size = names.at(name_position).size();
cout << "Encrypting name: " << names.at(name_position) << " of size " << name_size << endl << endl;
cout << "Position 1 " << names.at(name_position).at(0) << " is the same as ";
key_position = alphabet.find(names.at(name_position).at(0));
cout << key.at(key_position) << endl;
for (size_t i {0}; i < name_size; i++)
{
key_position = alphabet.find(names.at(name_position).at(i));
cout << "Finding " << names.at(key_position).at(i) << " in key at position " << key_position << endl;
cout << "Found encryption value of " << key.at(key_position) << " at position " << key_position << endl;
cout << "Changing " << names.at(key_position).at(i) << " to " << key.at(key_position) << endl;
names.at(name_position).at(i) = key.at(key_position);
}
/*
for (auto c: names.at(encrypt_input-1))
{
cout << "Converting " << c << " to ";
key_position = alphabet.find(c);
cout << key.at(key_position) << endl;
c = key.at(key_position);
cout << "C is now " << c << endl << endl;
}
*/
}
cout << names.at(encrypt_input-1) << endl;
break;
}
case 'q':
case 'Q':
cout << "Goodbye" << endl << endl;
break;
default:
cout << "Error 1: Invalid menu selection" << endl << endl;
break;
}
} while (selection != 'Q' && selection != 'q');
return 0;
}
Welcome to Stackoverflow! I agree entirely with PaulMcKenzie that such a big function is not the best for a variety of reasons - the immediate reasons are that its hard to read and hard to find problems - but there are more reasons as well.
Having said that you have a bug that I can see in the E case.
for (size_t i {0}; i < name_size; i++)
{
key_position = alphabet.find(names.at(name_position).at(i));
cout << "Finding " << names.at(key_position).at(i) << " in key at position " << key_position << endl;
cout << "Found encryption value of " << key.at(key_position) << " at position " << key_position << endl;
cout << "Changing " << names.at(key_position).at(i) << " to " << key.at(key_position) << endl;
names.at(name_position).at(i) = key.at(key_position);
}
Should be
for (unsigned int i{ 0 }; i < name_size; i++)
{
key_position = alphabet.find(names.at(name_position).at(i));
cout << "Finding " << names.at(name_position).at(i) << " in key at position " << key_position << endl;
cout << "Found encryption value of " << key.at(key_position) << " at position " << key_position << endl;
cout << "Changing " << names.at(name_position).at(i) << " to " << key.at(key_position) << endl;
names.at(name_position).at(i) = key.at(key_position);
}
ie key_position should be name_position in 2 places.
There may be other bugs, but this should stop the crashing and do the encoding right.
EDIT: On request of OP have added a new code fragment.
int i = 0; // position counter
for (auto c: names.at(encrypt_input-1))
{
cout << "Converting " << c << " to ";
key_position = alphabet.find(c);
cout << key.at(key_position) << endl;
c = key.at(key_position);
cout << "C is now " << c << endl << endl;
names.at(name_position).at(i++) = c; // update the names variable.
}
This should solve the problem you mentioned for the auto loop.
You're accessing an invalid location of names vector and the error / exception is showing that.
When you do this:
names.at( key_position ).at( i )
// ^^^
// It should be name_position
in this statement,
cout << "Finding " << names.at( key_position ).at( i ) << " in key at position " << key_position << endl;
you're accessing an invalid index of names whereas it should be:
names.at( name_position ).at( i )
and, that'll work because it access a valid index.
You're making the same mistake in this statement as well:
cout << "Changing " << names.at( key_position ).at( i ) << " to " << key.at( key_position ) << endl;
Correct these and it should work!
Tip:
It's time you read How to debug small programs.
It'll help you figure out what's wrong with your program in a more systematic way.
A few points regarding your code organization in general:
You should divide your program in functions instead of cluttering the main function.
You may write functions corresponding to each of your case in switch statement e.g. addName(), encryptName(), decryptName(), etc.
This modularity will definitely help you and other people to read, debug, maintain and extend your code easily and efficiently. In your case, it would also help you write an Minimal, Complete, and Verifiable example in no time.
Hope that helps!
Best of luck!
Happy coding!

C++ String Array search outputs for every item

I know it's somewhat confusing this title of question but I really need help.
I need to find a string in array with many strings. If the string is not found then the appropriate message is showed. However when I use for loop, it then shows this message for every string in array which is not found although it also shows found string... I hope you understand what I mean and sorry if i'm not making sense. here's my code:
void Store::search() {
string name;
cout << "Enter name of product you're searching: " << endl;
getline(cin, name);
for (int i = 0; i < quantity; i++) {
if (name.compare(database[i].name) == 0){
cout << "-------------<Product found!>-------------" << endl;
cout << "name: " << database[i].name << endl;
cout << "supplier: " << database[i].supplier << endl;
cout << "available quantity: " << database[i].quantity<< endl;
cout << "price per unit: " << database[i].price<< endl;
cout << "------------------------------------------" << endl;
}
else
{
cout << "Product doesn't exist in database!" << endl;
}
}
}
The code works for searching but how do I stop the output "Product doesn't exist in database!" for every item in array that is not found(even when searched item is found)?
Thank You in advance
You can use statement flag:
void Store::search()
{
string name;
bool found = false
cout << "Enter name of product you're searching: " << endl;
getline(cin, name);
for (int i = 0; i < quantity; i++)
{
if (name.compare(database[i].name) == 0){
cout << "-------------<Product found!>-------------" << endl;
cout << "name: " << database[i].name << endl;
cout << "supplier: " << database[i].supplier << endl;
cout << "available quantity: " << database[i].quantity<< endl;
cout << "price per unit: " << database[i].price<< endl;
cout << "------------------------------------------" << endl;
found = true;
break;
}
if (!found)
cout << "Product doesn't exist in database!" << endl;
}
You can also use std::find_if, which will make your code look something like:
auto it = std::find_if(databases.begin(), databases.end(), [&name](const auto &database) {return name.compare(database.name) == 0; });
if (it != databases.end())
{
cout << it->name << endl;
cout << "found" << endl;
}
else
{
cout << "not found" << endl;
}
Generally speaking, C++ offers many such features that more often than not will make your code shorter, improve readability and guarantee functionality
You can:
1. keep a bool variable to be set to true if the item is found in the for loop
2. add a break to immediately exit for loop when item is found
3. remove the else part, because it will print out "Product doesn't exist in database!" for each loop cycle if the item does not match
4. after the for loop, check if found is false to check if item does not exist in collection
bool found = false;
for (int i = 0; i < quantity; i++)
{
if (name.compare(database[i].name) == 0)
{
cout << "-------------<Product found!>-------------" << endl;
cout << "name: " << database[i].name << endl;
cout << "supplier: " << database[i].supplier << endl;
cout << "available quantity: " << database[i].quantity<< endl;
cout << "price per unit: " << database[i].price<< endl;
cout << "------------------------------------------" << endl;
found = true; // set "found" to true
break; // add a break to immediately exit for loop when item is found
}
}
if (!found)
{
cout << "Product doesn't exist in database!" << endl;
}
I assume you want to search a product in the database and print its details if found. Otherwise you want to notify user that the product was not found. If I understood you correctly, then you need to move the else statement out of 'for' loop, e.g.:
void Store::search() {
string name;
cout << "Enter name of product you're searching: " << endl;
getline(cin, name);
bool found = false;
for (int i = 0; i < quantity; i++) {
if (name.compare(database[i].name) == 0){
cout << "-------------<Product found!>-------------" << endl;
cout << "name: " << database[i].name << endl;
cout << "supplier: " << database[i].supplier << endl;
cout << "available quantity: " << database[i].quantity<< endl;
cout << "price per unit: " << database[i].price<< endl;
cout << "------------------------------------------" << endl;
found = true;
break;
}
}
if (!found)
{
cout << "Product doesn't exist in database!" << endl;
}
}
If your database may contain more products with the same name, remove 'break;' statement.
A more "modern C++" approach is to leverage the C++ algorithms (such as std::find_if), lambdas and maybe the auto specifier.
As example (assuming database is a std::vector or some kind of STL container):
auto it = std::find_if(database.begin(), database.end(), [&name](const auto& item) { return name.compare(item.name) == 0; });
if (it != database.end())
{
cout << it->name << endl;
cout << "found" << endl;
}
else
{
cout << "not found" << endl;
}

GetConsoleSelectionInfo C++

cI want to select some text with my cursor using the Mark Function from Console, but my code doesn't work ...
CONSOLE_SELECTION_INFO c;
if(GetConsoleSelectionInfo(&c))
{
while((c.dwFlags & CONSOLE_MOUSE_DOWN) == 0) { if(c.dwFlags) cout << c.dwFlags; }
cout << "SelectionAnchor: " << c.dwSelectionAnchor.X << " " << c.dwSelectionAnchor.Y;
cout << "RectangleSelection: " << c.srSelection.Top << " " << c.srSelection.Left << c.srSelection.Bottom << c.srSelection.Right;
}
else cout << "\n\nError: " << GetLastError();
Whatever I'm selecting or I'm doing, always c.dwFlags will be 0 ...