Search Results

Search found 1621 results on 65 pages for 'cout'.

Page 1/65 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Setting precision on std::cout in entire file scope - C++ iomanip

    - by Ivan
    Hi all, I'm doing some calculations, and the results are being save in a file. I have to output very precise results, near the precision of the double variable, and I'm using the iomanip setprecision(int) for that. The problem is that I have to put the setprecision everywhere in the output, like that: func1() { cout<<setprecision(12)<<value; cout<<setprecision(10)<<value2; } func2() { cout<<setprecision(17)<<value4; cout<<setprecision(3)<<value42; } And that is very cumbersome. Is there a way to set more generally the cout fixed modifier? Thanks

    Read the article

  • Strange beep when using cout

    - by Unknown
    Hello everyone, today when I was working on some code of mine I came across a beeping sound when printing a buffer to the screen. Here's the mysterious character that produces the beep: '' I don't know if you can see it, but my computer beeps when I try to print it like this: cout<<(char)7<<endl; Another point of interest is that the 'beep' doesn't originate from my on board beeper, but from my headphone/speaker Is this just my computer or there something wrong with the cout function? EDIT: But then why does printing this character produce the beep sound? does that mean that I could send other such characters through the cout function to produce different effects?

    Read the article

  • Indenting Paragraph With cout

    - by Eric
    Given a string of unknown length, how can you output it using cout so that the entire string displays as an indented block of text on the console? (so that even if the string wraps to a new line, the second line would have the same level of indentation) Example: cout << "This is a short string that isn't indented." << endl; cout << /* Indenting Magic */ << "This is a very long string that will wrap to the next line because it is a very long string that will wrap to the next line..." << endl; And the desired output: This is a short string that isn't indented. This is a very long string that will wrap to the next line because it is a very long string that will wrap to the next line... Edit: The homework assignment I'm working on is complete. The assignment has nothing to do with getting the output to format as in the above example, so I probably shouldn't have included the homework tag. This is just for my own enlightment. I know I could count through the characters in the string, see when I get to the end of a line, then spit out a newline and output -x- number of spaces each time. I'm interested to know if there is a simpler, idiomatic C++ way to accomplish the above.

    Read the article

  • calling std::cout.rdbuf() produces syntax error

    - by Mikepote
    Maybe I missed something, but I cant figure out why Visual Studio 2008 isn't seeing the rdbuf() procedure. Here is my code: 16. #include "DebugBuffer/BufferedStringBuf.h" 17. 18. BufferedStringBuf debug_buffer(256); 19. std::cout.rdbuf(&debug_buffer); The BufferedStringBuf class is from this page: http://www.devmaster.net/forums/showthread.php?t=7037 Which produces the following error: ...src\main.cpp(19) : error C2143: syntax error : missing ';' before '.' All I want to do is redirect std::cout to the Visual Studio Output window using OutputDebugString()..

    Read the article

  • C++ alignment when printing cout <<

    - by user69514
    Is there a way to align text when priting using cout? I'm using tabs, but when the words are too big they won't be aligned anymore Sales Report for September 15, 2010 Artist Title Price Genre Disc Sale Tax Cash Merle Blue 12.99 Country 4% 12.47 1.01 13.48 Richard Music 8.49 Classical 8% 7.81 0.66 8.47 Paula Shut 8.49 Classical 8% 7.81 0.72 8.49

    Read the article

  • Operator issues with cout

    - by BSchlinker
    I have a simple package class which is overloaded so I can output package data simply with cout << packagename. I also have two data types, name which is a string and shipping cost with a double. protected: string name; string address; double weight; double shippingcost; ostream &operator<<( ostream &output, const Package &package ) { output << "Package Information ---------------"; output << "Recipient: " << package.name << endl; output << "Shipping Cost (including any applicable fees): " << package.shippingcost; The problem is occurring with the 4th line (output << "Recipient:...). I'm receiving the error "no operator "<<" matches these operands". However, line 5 is fine. I'm guessing this has to do with the data type being a string for the package name. Any ideas?

    Read the article

  • Simple Detached pThread does not cancel! (cout blocks and interleaves even if mutexed)

    - by Gabriel
    I have a hard problem here, which I can not solve and do not find the right answer on the net: I have created a detached thread with a clean up routing, the problem is that on my Imac and Ubuntu 9.1 (Dual Core). I am not able to correctly cancel the detached thread in the fallowing code: #include <iostream> #include <pthread.h> #include <sched.h> #include <signal.h> #include <time.h> pthread_mutex_t mutex_t; using namespace std; static void cleanup(void *arg){ pthread_mutex_lock(&mutex_t); cout << " doing clean up"<<endl; pthread_mutex_unlock(&mutex_t); } static void *thread(void *aArgument) { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL); pthread_cleanup_push(&cleanup,NULL); int n=0; while(1){ pthread_testcancel(); sched_yield(); n++; pthread_mutex_lock(&mutex_t); cout << " Thread 2: "<< n<<endl; pthread_mutex_unlock(&mutex_t); } pthread_cleanup_pop(0); return NULL; } int main() { pthread_t thread_id; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); int error; if (pthread_mutex_init(&mutex_t,NULL) != 0) return 1; if (pthread_create(&thread_id, &attr, &(thread) , NULL) != 0) return 1; pthread_mutex_lock(&mutex_t); cout << "waiting 1s for thread...\n" <<endl; pthread_mutex_unlock(&mutex_t); int n =0; while(n<1E3){ pthread_testcancel(); sched_yield(); n++; pthread_mutex_lock(&mutex_t); cout << " Thread 1: "<< n<<endl; pthread_mutex_unlock(&mutex_t); } pthread_mutex_lock(&mutex_t); cout << "canceling thread...\n" <<endl; pthread_mutex_unlock(&mutex_t); if (pthread_cancel(thread_id) == 0) { //This doesn't wait for the thread to exit pthread_mutex_lock(&mutex_t); cout << "detaching thread...\n"<<endl; pthread_mutex_unlock(&mutex_t); pthread_detach(thread_id); while (pthread_kill(thread_id,0)==0) { sched_yield(); } pthread_mutex_lock(&mutex_t); cout << "thread is canceled"; pthread_mutex_unlock(&mutex_t); } pthread_mutex_lock(&mutex_t); cout << "exit"<<endl; pthread_mutex_unlock(&mutex_t); return 0; } When I replace the Cout with printf() i workes to the end "exit" , but with the cout (even locked) the executable hangs after outputting "detaching thread... It would be very cool to know from a Pro, what the problem here is?. Why does this not work even when cout is locked by a mutex!? Thanks a lot for your support!!

    Read the article

  • using cin and cout in textmate [migrated]

    - by That Guy
    I am usually a Java programmer, and have used textmate for that almost exclusively, but lately I started using C++ with it. but when i use even the most basic programs and incorporate the cin keyword, and run the program, I dont get an oppurtunity to put in anything during runtime and sometimes it inserts random values by itself! for example, if i ran this in textmate: #include <iostream> int stonetolb(int); int main() { using namespace std; int stone; cout << "enter the weight in stone"; cin >> stone; int pounds = stonetolb(stone); cout << stone << "stone = "; cout << pounds <<" pounds."; return 0; } int stonetolb(int sts) { return 14 * sts; } I would come out with the output: enter the weight in stone32767stone = 458738 pounds. Why is this happening, and how do I stop it?

    Read the article

  • Having an issue with overwriting an element of a file correctly (numeric)

    - by IngeniousHax
    This is an ATM style program, but currently it doesn't do exactly what I need it to do... I need to get the current balance, and when money is transferred from either checking or savings, it should add it to checking and subtract it from savings. which is does, but not correctly... Input example -=[ Funds Transfer ]=- -=[ Savings to Checking ]=- Account Name: nomadic Amount to transfer: $400 New Balance in Checking: $900 // original was 500 New Balance in Savings: $7.7068e+012 // this should now be 1100... Here is my code, it's a lot of code, but there are no errors, so throwing it into an IDE and compiling should be fairly quick for whoever would like to help. mainBankClass.h mainBankClass.h #ifndef MAINBANKCLASS_H #define MAINBANKCLASS_H #include <iostream> #include <fstream> #include <string> using namespace std; class Banking { protected: string checkAcctName, saveAcctName; // Name on the account int acctNumber[13]; // Account number float acctBalance, initSaveDeposit, initCheckDeposit, depAmt; // amount in account, and amount to deposit public: char getBalanceChoice(); // Get name on account for displaying relevant information char newAccountMenu(); // Create a new account and assign it a random account number void invalid(char *); // If an invalid option is chosen char menu(); // Print the main menu for the user. virtual float deposit(){ return 0; } // virtual function for deposits // virtual float withdrawal() = 0; // Virtual function for withdrawals void fatal(char *); // Handles fatal errors. Banking(); }; class Checking : public Banking { public: friend ostream operator<<(ostream &, Checking &); friend istream operator>>(istream &, Checking &); Checking operator <= (const Checking &) const; void newCheckingAccount(); void viewCheckingBalance(); void transferFromSaving(); float deposit() { return (acctBalance += depAmt); } }; class Saving : public Banking { public: friend ostream &operator<<(ostream &, Saving &); friend istream &operator>>(istream &, Saving &); Saving operator <= (const Saving &) const; void newSavingAccount(); void viewSavingBalance(); void transferFromChecking(); float deposit() { return (acctBalance += depAmt); } }; class checkAndSave : public Banking { public: void newCheckAndSave(); void viewBothBalances(); }; #endif bankAccount.cpp #include <iostream> #include <sstream> #include <string> #include <iomanip> #include <fstream> #include <time.h> #include "MainBankClass.h" /*****************************\ | BANKING CONSTRUCTOR | \*****************************/ Banking::Banking() { string acctName; // Name on the account acctNumber[13] = 0; // Account number acctBalance = 0; initCheckDeposit = 0; initSaveDeposit = 0; depAmt = 0; }; /********************************\ | The following code is to print the menu | | and recieve the users choice on what | | they want to do with the ATM | \********************************/ char Banking::menu() { char choice; system("cls"); cout << "\t\t -=[ Main Menu ]=- \n\n" << "\tA) Create New Account\n" << "\tB) View Account Balance\n" << "\tC) Transfer Funds From Checking To Savings\n" << "\tD) Transfer Funds From Savings To Checking\n" << "\tE) Exit\n" << "\n\n\tSelection: "; cin >> choice; cin.ignore(); choice = toupper(choice); while(!isalpha(choice)) { invalid("[!!] Invalid selection.\n[!!] Choose a valid option: "); cin >> choice; cin.ignore(); } return choice; } /*********************\ | Will read in account choic | | and display it for the user | \*********************/ char Banking::getBalanceChoice() { char choice; fstream saveFile("saving.dat", ios::in | ios::beg); system("cls"); cout << "\t\t -=[ View Account Balance ]=-\n\n"; cout << "A) View Checking Account\n" << "B) View Saving Account\n" << "C) View Checking \\ Saving Account\n" << endl; cout << "Choice: "; cin >> choice; choice = toupper(choice); if(!isalpha(choice)) fatal(" [!!] Invalid Choice"); return choice; } /***************************\ | Incase an invalid decision to made | | this throws the error message sent | | to it by the calling area | \***************************/ void Banking::invalid(char *msg) { cout << msg; } /*************************\ | Used if files can not be opened | | and exits with code 251: | | miscommunication with server | \*************************/ void Banking::fatal(char *msg) { cout << msg; exit(1); } /***************************\ | Create an account, either checking | | or savings, or both. | | Must should create a randomly | | generated account number that will | | correspond with each account. | \***************************/ /************************\ NOTE:: WILL BE UPDATED TO CONTAIN A PIN FOR ACCOUNT VERIFICATION *************************/ char Banking::newAccountMenu() { srand(time(NULL)); // Seed random generator with time initialized to NULL char acctChoice; // choice for the account type ofstream checkFile("checking.dat", ios::out | ios::app); // For saving checking accounts ofstream saveFile("saving.dat", ios::out | ios::app); // For saving savings accounts system("cls"); cout << "\t\t-=[ New Account Creation ]=-\n\n" << endl; cout << "A) Checking Account\n" << "B) Savings Account\n" << "C) Checking and Saving Account\n" << endl; cout << "New account type: "; cin >> acctChoice; acctChoice = toupper(acctChoice); cin.clear(); cin.sync(); return acctChoice; } /********************************************************************* ********************************************************************** CHECKING ACCOUNT CODE ********************************************************************** **********************************************************************/ // New Checking Account Creation void Checking::newCheckingAccount() { system("cls"); ofstream checkFile("checking.dat", ios::out | ios::app); // For saving checking accounts cout << "\t\t -=[ New Checking Account ]=- \n" << endl; cout << "Name of the main holder to be on the account: "; getline(cin, checkAcctName); cout << "Initial deposit amount: $"; cin >> initCheckDeposit; if(initCheckDeposit <= 0) { while(initCheckDeposit <= 0) { invalid("[!!] 0 or negative amount entered\nMaybe a typo?\n"); cout << "Deposit Amount: $"; cin >> initCheckDeposit; } } if(!checkFile) fatal("[!!] Fatal Error 251: Miscommunication with server\n"); checkFile << checkAcctName << endl; for(int j = 0; j < 13; j++) { acctNumber[j] = (rand() % 10); // Build a random checking account number checkFile << acctNumber[j]; } checkFile << endl; checkFile << initCheckDeposit << endl; checkFile.close(); } void Checking::viewCheckingBalance() { fstream checkFile("checking.dat", ios::in | ios::beg); string name; int i = 0; double balance = 0; system("cls"); cout << "\t\t -=[ View Checking Account ]=-\n\n" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(checkFile, checkAcctName); while(name != checkAcctName && !checkFile.fail()) { i++; getline(checkFile, checkAcctName); } if(name == checkAcctName) { system("cls"); cout << "\t\t -=[ Checking Account Balance ]=-\n\n" << endl; cout << "Account Name: " << checkAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; checkFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; checkFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; } else fatal("[!!] Invalid Account\n"); checkFile.close(); getchar(); } void Checking::transferFromSaving() // Move funds FROM SAVINGS to CHECKING { system("cls"); string name; long checkPos = 0; long savePos = 0; float savingBalance = 0; string saveAcctName; int i = 0; cin.clear(); fstream saveFile("saving.dat", ios::in | ios::out | ios::beg); fstream checkFile("checking.dat", ios::in | ios::out | ios::beg); cout << "\t\t-=[ Funds Transfer ]=-" << endl; cout << "\t\t-=[ Savings to Checking ]=-" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(checkFile, checkAcctName); while(name != checkAcctName && !checkFile.fail()) { i++; getline(checkFile, checkAcctName); } getline(saveFile, saveAcctName); while(name != saveAcctName && !saveFile.fail()) { i = 0; i++; getline(saveFile, saveAcctName); } if(name == checkAcctName) { cout << "Amount to transfer: $"; float depAmt = 0; cin >> depAmt; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; checkFile.get(input_number); converter << input_number; converter >> acctNumber[j]; } checkPos = checkFile.tellg(); // if the file is found, get the position of acctBalance and store it in ptrPos checkFile.seekg(checkPos); checkFile >> acctBalance; savePos = saveFile.tellg(); saveFile.seekg(savePos); // sending the cursor in the file to ptrPos + 1 to ignore white space saveFile >> savingBalance; if(savingBalance < depAmt) // if checking account does not have enough funds, exit with NSF code fatal("[!!] Insufficient Funds\n"); acctBalance += depAmt; // can be changed to an overloaded operator savingBalance -= depAmt; // can be changed to an overloaded operator checkFile.seekp(checkPos); // go to position previously set above checkFile << acctBalance; // write new balance to checkFile saveFile.seekp(savePos); // same thing as above comment saveFile << savingBalance; // write new balance to saveFile cout << "New Balance in Checking: $" << acctBalance << endl; // will be removed later cout << "New Balance in Savings: $" << savingBalance << endl; // will be removed later aswell } else fatal("[!!] Linked accounts do not exist.\n"); // if account is not found saveFile.close(); checkFile.close(); } /******************************************************** ******************************************************** SAVING ACCOUNT CODE ********************************************************* *********************************************************/ void Saving::newSavingAccount() { system("cls"); ofstream saveFile("saving.dat", ios::out | ios::app); // For saving savings accounts cout << "\t\t -=[ New Savings Account ]=- \n" << endl; cout << "Name of the main holder to be on account: "; getline(cin, saveAcctName); cout << "Deposit Amount: $"; cin >> initSaveDeposit; if(initSaveDeposit <= 0) { while(initSaveDeposit <= 0) { invalid("[!!]0 or negative value entered.\nPerhaps a typo?\n"); cout << "Deposit amount: $"; cin >> initSaveDeposit; } } if(!saveFile) fatal("[!!] Fatal Error 251: Miscommunication with server\n"); saveFile << saveAcctName << endl; for(int j = 0; j < 13; j++) { acctNumber[j] = (rand() % 10); saveFile << acctNumber[j]; } saveFile << endl; saveFile << initSaveDeposit << endl; saveFile.close(); } void Saving::viewSavingBalance() { string name; int i = 0; fstream saveFile("saving.dat", ios::in | ios::beg); cin.clear(); system("cls"); cout << "\t\t -=[ View Saving Account ]=-\n\n" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(saveFile, saveAcctName); while(name != saveAcctName && !saveFile.fail()) { i++; getline(saveFile, saveAcctName); } if(name == saveAcctName) { system("cls"); cout << "\t\t -=[ Saving Account Balance ]=-\n\n" << endl; cout << "Account Name: " << saveAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; saveFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; saveFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; } else fatal("[!!] Invalid Account\n"); saveFile.close(); getchar(); } // NEED TO WORK ON THIS PORTION TOMORROW AND MONDAY, ADD OVERLOADED OPS FOR ASSIGNMENT!!!!!!! void Saving::transferFromChecking() // This is to take money FROM checking and ADD IT TO SAVING { system("cls"); string name; long savePos = 0; long checkPos = 0; float checkingBalance = 0; string checkAcctName; int i = 0; cin.clear(); fstream saveFile("saving.dat", ios::in | ios::out | ios::beg); fstream checkFile("checking.dat", ios::in | ios::out | ios::beg); cout << "\t\t-=[ Funds Transfer ]=-" << endl; cout << "\t\t-=[ Checking to Savings ]=-" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(saveFile, saveAcctName); getline(checkFile, checkAcctName); while(name != saveAcctName && name != checkAcctName && !saveFile.fail() && !checkFile.fail()) { i++; getline(saveFile, saveAcctName); getline(checkFile, checkAcctName); } if(name == saveAcctName) { cout << "Amount to transfer: $"; float depAmt = 0; cin >> depAmt; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; saveFile.get(input_number); converter << input_number; converter >> acctNumber[j]; } savePos = saveFile.tellg(); // if the file is found, get the position of acctBalance and store it in ptrPos saveFile.seekg(savePos); saveFile >> acctBalance; checkPos = checkFile.tellg(); checkFile.seekg(checkPos); // if file is found, store current position of the cursor to ptrPos checkFile >> checkingBalance; if(checkingBalance < depAmt) // if checking account does not have enough funds, exit with NSF code fatal("[!!] Insufficient Funds\n"); // Can also place overloaded op here acctBalance += depAmt; // can be changed to an overloaded operator checkingBalance -= depAmt; // can be changed to an overloaded operator saveFile.seekg(savePos); // go to position previously set above saveFile << acctBalance; // write new balance to saveFile checkFile.seekg(checkPos); // same thing as above comment checkFile << checkingBalance; // write new balance to checkFile cout << "New Balance in Savings: $" << acctBalance << endl; // will be removed later cout << "New Balance in Checking: $" << checkingBalance << endl; // will be removed later aswell } else fatal("[!!] Linked accounts do not exist.\n"); // if account is not found saveFile.close(); checkFile.close(); } /******************************************** ******************************************** CHECK AND SAVE CODE ********************************************** **********************************************/ void checkAndSave::newCheckAndSave() { system("cls"); ofstream saveFile("saving.dat", ios::out | ios::app); // For saving savings accounts ofstream checkFile("checking.dat", ios::out | ios::app); // For saving checking accounts cout << "\t -=[ New Checking & Saving Account ]=- \n" << endl; cout << "Name of the main holder to be on account: "; getline(cin, checkAcctName); saveAcctName = checkAcctName; cout << "Checking Deposit Amount: $"; cin >> initCheckDeposit; if(initCheckDeposit <= 0) { while(initCheckDeposit <= 0) { invalid("[!!] 0 or negative amount entered\nMaybe a typo?\n"); cout << "Deposit Amount: $"; cin >> initCheckDeposit; } } cout << "Saving Deposit Amount: $"; cin >> initSaveDeposit; if(initSaveDeposit <= 0) { while(initSaveDeposit <= 0) { invalid("[!!]0 or negative value entered.\nPerhaps a typo?\n"); cout << "Deposit amount: $"; cin >> initSaveDeposit; } } if(!saveFile || !checkFile) fatal("[!!] Fatal Error 251: Miscommunication with server\n"); checkFile << checkAcctName << endl; saveFile << saveAcctName << endl; for(int j = 0; j < 13; j++) { acctNumber[j] = (rand() % 10); checkFile << acctNumber[j]; saveFile << acctNumber[j]; } saveFile << endl; saveFile << initSaveDeposit << endl; checkFile << endl; checkFile << initCheckDeposit << endl; checkFile.close(); saveFile.close(); } void checkAndSave::viewBothBalances() { string name; int i = 0; fstream checkFile("checking.dat", ios::in | ios::beg); fstream saveFile("saving.dat", ios::in | ios::beg); system("cls"); cin.clear(); cout << "\t-=[ Saving & Checking Account Balance ]=-\n\n" << endl; cout << "Account Name: "; cin.sync(); getline(cin, name); getline(checkFile, checkAcctName); saveAcctName = name; /**********************\ | Checking Account portion | | of the checking & savings | | overview | \**********************/ while(name != checkAcctName && !checkFile.fail()) { i++; getline(checkFile, checkAcctName); } system("cls"); if(name != checkAcctName && checkFile.fail()) invalid("\n\n[!!] No Checking Account Found\n"); cout << "\t\t -=[ Checking Account ]=- \n" << endl; cout << "Account Name: " << checkAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; checkFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; checkFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; /*********************\ | Saving Account portion | | of the checking & saving | | overview | \*********************/ getline(saveFile, saveAcctName); while(name != saveAcctName && !saveFile.fail()) { i++; getline(saveFile, saveAcctName); } if(name != saveAcctName && saveFile.fail()) invalid("\n\n[!!] No Saving Account Found\n"); if(name == saveAcctName) { cout << "\t\t -=[ Saving Account ]=-\n\n" << endl; cout << "Account Name: " << saveAcctName << "\n"; cout << "Account Number: "; for(int j = 0; j < 13; j++) { char input_number; stringstream converter; saveFile.get(input_number); converter << input_number; converter >> acctNumber[j]; cout << acctNumber[j]; } // if balance a problem, try the below commented out line // checkFile.ignore(numeric_limits<streamsize>::max(), '\n'); cout << endl; saveFile >> acctBalance; cout << "Balance: $" << fixed << showpoint << setprecision(2) << acctBalance << endl; } if(name != saveAcctName && name != checkAcctName && saveFile.fail() && checkFile.fail()) fatal("[!!] No Accounts Have Been Found\n"); checkFile.close(); saveFile.close(); getchar(); } Main.cpp #include <iostream> #include "MainBankClass.h" using namespace std; int main() { Banking bank; Checking check; Saving save; checkAndSave CanS; char choice; choice = bank.menu(); // Call the banking menu switch(choice) { case 'A': choice = bank.newAccountMenu(); switch(choice) { case 'A': check.newCheckingAccount(); break; case 'B': save.newSavingAccount(); break; case 'C': CanS.newCheckAndSave(); break; default: system("cls"); bank.fatal("[!!] Invalid option\n"); break; } break; /***********************************************/ case 'B': choice = bank.getBalanceChoice(); switch(choice) { case 'A': check.viewCheckingBalance(); break; case 'B': save.viewSavingBalance(); break; case 'C': CanS.viewBothBalances(); break; default: bank.fatal("Invalid decision\n"); break; } /*************************************************/ break; case 'C': check.transferFromSaving(); break; case 'D': save.transferFromChecking(); break; case 'E': system("cls"); cout << "\t\t-=[ Disconnecting From System ]=-\n"; cout << "\t\t\t Thank you" << endl; cout << "\t\t Have a nice day!" << endl; exit(1); break; default: system("cls"); bank.invalid("\n\n\n\n\t\t [+] Invalid Selection \n\t\t[+] Disconnecting From System \n\t\t\tGood-bye \n\n\n\n\n\n\n"); exit(1); break; } return 0; }

    Read the article

  • What can explain std::cout not to display anything ?

    - by Benoît
    For whatever reason, std::cout does not display anything with my application. The description of my development environment follows. I am working on a Qt application using Qt Creator. Since Qt Creator can't be launched from my station (XP64), i am currently developping it with Visual Studio 2008 and the Qt plugin (by importing the .pro project file). Everything seems fine and the application works. In some cases (depending on command line arguments), i don't want to launch the HIM, just to display a few sentences in the CLI (command line required arguments, for instance). I don't get any error, but nothing is displayed. The corresponding code, which i am sure is run is the (classical) following : std::cout << "is this going to be displayed ?" << std::endl; Do you have any idea why nothing is displayed ?

    Read the article

  • Insight into how things get printed onto the screen (cout,printf) and origin of really complex stuff

    - by sil3nt
    I've always wondered this, and still haven't found the answer. Whenever we use "cout" or "printf" how exactly is that printed on the screen?. How does the text come out as it does...(probably quite a vague question here, ill work with whatever you give me.). So basically how are those functions made?..is it assembly?, if so where does that begin?. This brings on more questions like how on earth have they made openGl/directx functions.. break it down people break it down.:)

    Read the article

  • I was stuck in implementing Simple Ftp with Winsock [migrated]

    - by user67449
    I want to implement a SimpleFtp with Winsock. But I was stuck in the maybe the file stream reading and writing. This is the Server. #include <WinSock2.h> #include <memory.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define MAX_FILE_NAME 100 #define DATA_PACK_SIZE 80*1000 // ??DataPack?????80KB #define SOCKKET_BUFFER_SIZE 80*1000 // socket??? #define FILE_BUFFER_SIZE DATA_PACK_SIZE-MAX_FILE_NAME-4*sizeof(int)-sizeof(u_long) //?????,??,??????content????? #define CONTENT_SIZE FILE_BUFFER_SIZE // DataPack?????content??? // Define a structure to hold the content of a file typedef struct FilePack{ char fName[MAX_FILE_NAME]; // File's name int fLen; // File's length int packNum; // Number of the DataPack int packLen; // DataPack's length int packCount; int contenLen; // the content length the DataPack actually holds u_long index; // ?????????? char content[CONTENT_SIZE]; // DataPack?????? }DataPack, *pDataPack; void WinsockInitial(){ WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested=MAKEWORD(2,2); err=WSAStartup(wVersionRequested, &wsaData); if(err!=0){ cout<<"Error at WSAStartup()."<<endl; exit(0); } if( LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2 ){ cout<<"Error at version of Winsock. "<<endl; WSACleanup(); exit(0); } } void SockBind(SOCKET sock, int port, sockaddr_in &addrsock){ addrsock.sin_family=AF_INET; addrsock.sin_port=htons(port); addrsock.sin_addr.S_un.S_addr=htonl(INADDR_ANY); if( bind(sock, (sockaddr*)&addrsock, sizeof(addrsock)) == SOCKET_ERROR ){ cout<<"Error at bind(). Error: "<<GetLastError()<<endl; closesocket(sock); WSACleanup(); exit(0); } } void SockListen(SOCKET sock, int bak){ int err=listen(sock, bak); if(err==SOCKET_ERROR){ cout<<"Error at listen()."<<WSAGetLastError()<<endl; closesocket(sock); WSACleanup(); exit(0); } } int SockSend(DataPack &dataPack, SOCKET sock, char *sockBuf){ int bytesLeft=0, bytesSend=0; int idx=0; bytesLeft=sizeof(dataPack); // ?DataPack?????sockBuf??? memcpy(sockBuf, &dataPack, sizeof(dataPack)); while(bytesLeft>0){ bytesSend=send(sock, &sockBuf[idx], bytesLeft, 0); if(bytesSend==SOCKET_ERROR){ cout<<"Error at send()."<<endl; return 1; } bytesLeft-=bytesSend; idx+=bytesSend; } return 0; } int GetFileLen(FILE *fp){ // ?????? if(fp==NULL){ cout<<"Invalid argument. Error at GetFileLen()."<<endl; exit(0); } fseek(fp, 0, SEEK_END); int tempFileLen=ftell(fp); fseek(fp, 0, SEEK_SET); return tempFileLen; } int main(){ int err; sockaddr_in addrServ; int port=8000; // Initialize Winsock WinsockInitial(); // Create a socket SOCKET sockListen=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockListen==INVALID_SOCKET){ cout<<"Error at socket()."<<endl; WSACleanup(); return 1; } // Bind the socket. SockBind(sockListen, port, addrServ); // Listen for incoming connection requests cout<<"Waiting for incoming connection requests..."<<endl; SockListen(sockListen, 5); // Accept the connection request. sockaddr_in addrClient; int len=sizeof(addrClient); SOCKET sockConn=accept(sockListen, (sockaddr*)&addrClient, &len); if(sockConn!=INVALID_SOCKET){ cout<<"Connected to client successfully."<<endl; } // Set the buffer size of socket char sockBuf[SOCKKET_BUFFER_SIZE]; int nBuf=SOCKKET_BUFFER_SIZE; int nBufLen=sizeof(nBuf); err=setsockopt(sockConn, SOL_SOCKET, SO_SNDBUF, (char*)&nBuf, nBufLen); if(err!=0){ cout<<"Error at setsockopt(). Failed to set buffer size for socket."<<endl; exit(0); } //??????????? err = getsockopt(sockConn, SOL_SOCKET, SO_SNDBUF, (char*)&nBuf, &nBufLen); if( SOCKKET_BUFFER_SIZE != nBuf){ cout<<"Error at setsockopt(). ?socket????????"<<endl; closesocket(sockListen); closesocket(sockConn); WSACleanup(); exit(0); } //------------------------------------------------------------------------// DataPack dataPackSend; memset(&dataPackSend, 0, sizeof(dataPackSend)); int bytesRead; int bytesLeft; int bytesSend; int packCount; // Counts how many DataPack needed FILE *frp; // Used to read if(strcpy_s(dataPackSend.fName, "music.mp3")!=0){ cout<<"Error at strcpy_s()."<<endl; return 1; } // Open the file in read+binary mode err=fopen_s(&frp, dataPackSend.fName, "rb"); if(err!=0){ cout<<"Error at fopen_s()."<<endl; return 1; } char fileBuf[FILE_BUFFER_SIZE]; // Set the buffer size of File if(setvbuf(frp, fileBuf, _IONBF, FILE_BUFFER_SIZE)!=0){ cout<<"Error at setvbuf().Failed to set buffer size for file."<<endl; closesocket(sockListen); closesocket(sockConn); WSACleanup(); exit(0); } // Get file's length int fileLen=GetFileLen(frp); cout<<"File ???:"<<fileLen<<" bytes."<<endl; // Calculate how many DataPacks needed packCount=ceil( (double)fileLen/CONTENT_SIZE ); cout<<"File Length: "<<fileLen<<" "<<"Content Size: "<<CONTENT_SIZE<<endl; cout<<"???"<<packCount<<" ?DataPack"<<endl; int i=0; for(i=0; i<packCount; i++){ //?????dataPackSend????? memset(&dataPackSend, 0, sizeof(dataPackSend)); // Fill the dataPackSend if(strcpy_s(dataPackSend.fName, "abc.txt")!=0){ cout<<"Error at strcpy_s()."<<endl; return 1; } dataPackSend.packLen=DATA_PACK_SIZE; dataPackSend.fLen=fileLen; dataPackSend.packCount=packCount; if( packCount==1 ){ //??DataPack??? bytesRead=fread(fileBuf, 1, dataPackSend.fLen, frp); dataPackSend.contenLen=dataPackSend.fLen; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=0; //???????DataPack // ?????dataPackSend?Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack"<<endl; } }else if( packCount>1 && i<(packCount-1) ){ // ???(???????) bytesRead=fread(fileBuf, 1, CONTENT_SIZE, frp); dataPackSend.contenLen=CONTENT_SIZE; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=i; //?dataPackSend??????Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack."<<endl; } }else{ // ????? bytesRead=fread(fileBuf, 1, (dataPackSend.fLen-i*CONTENT_SIZE), frp); dataPackSend.contenLen=dataPackSend.fLen-i*CONTENT_SIZE; memcpy(dataPackSend.content, fileBuf, bytesRead); dataPackSend.packNum=i; //?dataPackSend???Client? if( SockSend(dataPackSend, sockConn, sockBuf)==0 ){ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack."<<endl; } } } fclose(frp); closesocket(sockListen); closesocket(sockConn); WSACleanup(); return 0; } And this is Client. #include <WinSock2.h> #include <memory.h> #include <stdio.h> #include <iostream> using namespace std; #pragma comment(lib, "ws2_32.lib") #define MAX_FILE_NAME 100 #define DATA_PACK_SIZE 80*1000 // ??DataPack?????80KB #define SOCKKET_BUFFER_SIZE 80*1000 // socket??? #define FILE_BUFFER_SIZE DATA_PACK_SIZE-MAX_FILE_NAME-4*sizeof(int)-sizeof(u_long) //?????,??,??????content????? #define CONTENT_SIZE FILE_BUFFER_SIZE // DataPack?????content??? // Define a structure to hold the content of a file typedef struct FilePack{ char fName[MAX_FILE_NAME]; // File's name int fLen; // File's length int packNum; // Number of the DataPack int packLen; // DataPack's length int packCount; //DataPack??? int contenLen; // the content length the DataPack actually holds u_long index; // ?????????? char content[CONTENT_SIZE]; // DataPack?????? }DataPack, *pDataPack; void WinsockInitial(){ WSADATA wsaData; WORD wVersionRequested; int err; wVersionRequested=MAKEWORD(2,2); err=WSAStartup(wVersionRequested, &wsaData); if(err!=0){ cout<<"Error at WSAStartup()."<<endl; exit(0); } if( LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=2 ){ cout<<"Error at version of Winsock. "<<endl; WSACleanup(); exit(0); } } int SockRecv(SOCKET sock, char *sockBuf){ int bytesLeft, bytesRecv; int idx=0; bytesLeft=DATA_PACK_SIZE; while(bytesLeft>0){ bytesRecv=recv(sock, &sockBuf[idx], bytesLeft, 0); if(bytesRecv==SOCKET_ERROR){ cout<<"Error at recv()."<<endl; return 1; } bytesLeft-=bytesRecv; idx+=bytesRecv; } return 0; } int main(){ int err; sockaddr_in addrServ; int port=8000; // Initialize Winsock WinsockInitial(); // Create a socket SOCKET sockClient=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockClient==INVALID_SOCKET){ cout<<"Error at socket()."<<endl; WSACleanup(); return 1; } // Set the buffer size of socket char sockBuf[SOCKKET_BUFFER_SIZE]; int nBuf=SOCKKET_BUFFER_SIZE; int nBufLen=sizeof(nBuf); err=setsockopt(sockClient, SOL_SOCKET, SO_RCVBUF, (char*)&nBuf, nBufLen); if(err!=0){ cout<<"Error at setsockopt(). Failed to set buffer size for socket."<<endl; exit(0); } //??????????? err = getsockopt(sockClient, SOL_SOCKET, SO_RCVBUF, (char*)&nBuf, &nBufLen); if( SOCKKET_BUFFER_SIZE != nBuf){ cout<<"Error at getsockopt(). ?socket????????"<<endl; closesocket(sockClient); WSACleanup(); exit(0); } // Connect to the Server addrServ.sin_family=AF_INET; addrServ.sin_port=htons(port); addrServ.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); err=connect(sockClient, (sockaddr*)&addrServ, sizeof(sockaddr)); if(err==SOCKET_ERROR){ cout<<"Error at connect()."<<GetLastError()<<endl; closesocket(sockClient); WSACleanup(); return 1; }else{ cout<<"Connected to the FTP Server successfully."<<endl; } /* int i=0; int bytesRecv, bytesLeft, bytesWrite; int packCount=0, fLen=0; DataPack dataPackRecv; //?????? SockRecv(sockClient, sockBuf); memcpy(&dataPackRecv, sockBuf, sizeof(dataPackRecv)); cout<<"???? "<<dataPackRecv.packNum<<" ?DataPack."<<endl; cout<<"?DataPack??fName????: "<<dataPackRecv.fName<<endl; //??????? packCount=dataPackRecv.packCount; cout<<"?? "<<packCount<<" ?DataPack."<<endl; fLen=dataPackRecv.fLen; // Create a local file to write into FILE *fwp; err=fopen_s(&fwp, dataPackRecv.fName, "wb"); if(err!=0){ cout<<"Error at creat fopen_s(). Failed to create a local file to write into."<<endl; return 1; } // Set the buffer size of File char fileBuf[FILE_BUFFER_SIZE]; if(setvbuf(fwp, fileBuf, _IONBF, FILE_BUFFER_SIZE)!=0){ cout<<"Error at setvbuf().Failed to set buffer size for file."<<endl; memset(fileBuf, 0, sizeof(fileBuf)); closesocket(sockClient); WSACleanup(); exit(0); } //???????content???? memcpy(fileBuf, dataPackRecv.content, sizeof(dataPackRecv.content)); bytesWrite=fwrite(fileBuf, 1, sizeof(fileBuf), fwp); if(bytesWrite<sizeof(fileBuf)){ cout<<"Error at fwrite(). Failed to write the content of dataPackRecv to local file."<<endl; } //?????packCount-1????????????????? for(int i=1; i<packCount; i++){ // ????????? memset(sockBuf, 0, sizeof(sockBuf)); memset(&dataPackRecv, 0, sizeof(dataPackRecv)); memset(fileBuf, 0, sizeof(fileBuf)); SockRecv(sockClient, sockBuf); memcpy(&dataPackRecv, sockBuf, sizeof(dataPackRecv)); cout<<"???? "<<dataPackRecv.packNum<<" ?DataPack."<<endl; //???? memcpy(fileBuf, dataPackRecv.content, dataPackRecv.contenLen); bytesWrite=fwrite(fileBuf, 1, dataPackRecv.contenLen, fwp); if(bytesWrite<dataPackRecv.contenLen){ cout<<"Error at fwrite(). Failed to write the content of dataPackRecv to local file."<<endl; } } if( (i+1)==packCount ){ cout<<"??DataPack????????!"<<endl; } fclose(fwp); closesocket(sockClient); WSACleanup(); return 0;*/ }

    Read the article

  • Qt Graphics et performances - le coût des commodités, un article de Gunnar traduit par Guillaume Belz

    Le 11 décembre 2009, la documentation de QPainter subissait un énorme ajout concernant l'optimisation de son utilisation. En effet, le bon usage de cet outil n'était pas accessible à tous, il n'était pas présenté dans la documentation. Ceci ne fut qu'un prétexte à une série d'articles sur l'optimisation de QPainter et de Qt Graphics en général. Voici donc le premier article de cette série, les autres sont en préparation : Qt Graphics et performances : ce qui est critique et ce qui ne l'est pas Pensez-vous que cet ajout à la documentation de QPainter sera utile ? Trouvez-vous les performances de vos applications trop faibles ?...

    Read the article

  • Cannot cout data [C++] [metaprogramming]

    - by atch
    Hi, Guys, reffering to last post I'm trying to output data while template is instantiated template <unsigned long N> struct binary { std::cout << N;//<---------------------------------I'M TRYING HERE static unsigned const value = binary<N/10>::value << 1 // prepend higher bits | N%10; // to lowest bit but I'm getting an error: 'Error 2 error C2886: 'std::cout' : symbol cannot be used in a member using- declaration ' Thanks for help P.S. And could anyone explain why actually I can't do that?

    Read the article

  • The question regarding cerr cout and clog

    - by skydoor
    Can anybody explain the difference between cerr cout and clog and why does different objects are proposed? I know the differences are as below: 1) cout can redirected but cerr can't 2) clog can use buffer. I am confused about the point 2, I am grateful if anybody can elaborate it more.

    Read the article

  • how to cout a vector of structs (that's a class member, using extraction operator)

    - by Julz
    hi, i'm trying to simply cout the elements of a vector using an overloaded extraction operator. the vector contians Point, which is just a struct containing two doubles. the vector is a private member of a class called Polygon, so heres my Point.h #ifndef POINT_H #define POINT_H #include <iostream> #include <string> #include <sstream> struct Point { double x; double y; //constructor Point() { x = 0.0; y = 0.0; } friend std::istream& operator >>(std::istream& stream, Point &p) { stream >> std::ws; stream >> p.x; stream >> p.y; return stream; } friend std::ostream& operator << (std::ostream& stream, Point &p) { stream << p.x << p.y; return stream; } }; #endif my Polygon.h #ifndef POLYGON_H #define POLYGON_H #include "Segment.h" #include <vector> class Polygon { //insertion operator needs work friend std::istream & operator >> (std::istream &inStream, Polygon &vertStr); // extraction operator friend std::ostream & operator << (std::ostream &outStream, const Polygon &vertStr); public: //Constructor Polygon(const std::vector<Point> &theVerts); //Default Constructor Polygon(); //Copy Constructor Polygon(const Polygon &polyCopy); //Accessor/Modifier methods inline std::vector<Point> getVector() const {return vertices;} //Return number of Vector elements inline int sizeOfVect() const {return vertices.size();} //add Point elements to vector inline void setVertices(const Point &theVerts){vertices.push_back (theVerts);} private: std::vector<Point> vertices; }; and Polygon.cc using namespace std; #include "Polygon.h" // Constructor Polygon::Polygon(const vector<Point> &theVerts) { vertices = theVerts; } //Default Constructor Polygon::Polygon(){} istream & operator >> (istream &inStream, Polygon::Polygon &vertStr) { inStream >> ws; inStream >> vertStr; return inStream; } // extraction operator ostream & operator << (ostream &outStream, const Polygon::Polygon &vertStr) { outStream << vertStr.vertices << endl; return outStream; } i figure my Point insertion/extraction is right, i can insert and cout using it and i figure i should be able to just...... cout << myPoly[i] << endl; in my driver? (in a loop) or even... cout << myPoly[0] << endl; without a loop? i've tried all sorts of myPoly.at[i]; myPoly.vertices[i]; etc etc also tried all veriations in my extraction function outStream << vertStr.vertices[i] << endl; within loops, etc etc. when i just create a... vector<Point> myVect; in my driver i can just... cout << myVect.at(i) << endl; no problems. tried to find an answer for days, really lost and not through lack of trying!!! thanks in advance for any help. please excuse my lack of comments and formatting also there's bits and pieces missing but i really just need an answer to this problem thanks again

    Read the article

  • Re: Help with Boost Grammar

    - by Decmac04
    I have redesigned and extended the grammar I asked about earlier as shown below: // BIFAnalyser.cpp : Defines the entry point for the console application. // // /*============================================================================= Copyright (c) Temitope Jos Onunkun 2010 http://www.dcs.kcl.ac.uk/pg/onun/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ //////////////////////////////////////////////////////////////////////////// // // // B Machine parser using the Boost "Grammar" and "Semantic Actions". // // // //////////////////////////////////////////////////////////////////////////// include include include include include include //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; //////////////////////////////////////////////////////////////////////////// // // Semantic Actions // //////////////////////////////////////////////////////////////////////////// // // namespace { //semantic action function on individual lexeme void do_noint(char const* start, char const* end) { string str(start, end); if (str != "NAT1") cout << "PUSH(" << str << ')' << endl; } //semantic action function on addition of lexemes void do_add(char const*, char const*) { cout << "ADD" << endl; // for(vector::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) // cout << *vi << " "; } //semantic action function on subtraction of lexemes void do_subt(char const*, char const*) { cout << "SUBTRACT" << endl; } //semantic action function on multiplication of lexemes void do_mult(char const*, char const*) { cout << "\nMULTIPLY" << endl; } //semantic action function on division of lexemes void do_div(char const*, char const*) { cout << "\nDIVIDE" << endl; } // // vector flowTable; //semantic action function on simple substitution void do_sSubst(char const* start, char const* end) { string str(start, end); //use boost tokenizer to break down tokens typedef boost::tokenizer Tokenizer; boost::char_separator sep(" -+/*:=()",0,boost::drop_empty_tokens); // char separator definition Tokenizer tok(str, sep); Tokenizer::iterator tok_iter = tok.begin(); pair dependency; //create a pair object for dependencies //create a vector object to store all tokens vector dx; // int counter = 0; // tracks token position for(tok.begin(); tok_iter != tok.end(); ++tok_iter) //save all tokens in vector { dx.push_back(*tok_iter ); } counter = dx.size(); // vector d_hat; //stores set of dependency pairs string dep; //pairs variables as string object // dependency.first = *tok.begin(); vector FV; for(int unsigned i=1; i < dx.size(); i++) { // if(!atoi(dx.at(i).c_str()) && (dx.at(i) !=" ")) { dependency.second = dx.at(i); dep = dependency.first + "|-" + dependency.second + " "; d_hat.push_back(dep); vector<string> row; row.push_back(dependency.first); //push x_hat into first column of each row for(unsigned int j=0; j<2; j++) { row.push_back(dependency.second);//push an element (column) into the row } flowTable.push_back(row); //Add the row to the main vector } } //displays internal representation of information flow table cout << "\n****************\nDependency Table\n****************\n"; cout << "X_Hat\tDx\tG_Hat\n"; cout << "-----------------------------\n"; for(unsigned int i=0; i < flowTable.size(); i++) { for(unsigned int j=0; j<2; j++) { cout << flowTable[i][j] << "\t "; } if (*tok.begin() != "WHILE" ) //if there are no global flows, cout << "\t{}"; //display empty set cout << "\n"; } cout << "***************\n\n"; for(int unsigned j=0; j < FV.size(); j++) { if(FV.at(j) != dependency.second) dep = dependency.first + "|-" + dependency.second + " "; d_hat.push_back(dep); } cout << "PUSH(" << str << ')' << endl; cout << "\n*******\nDependency pairs\n*******\n"; for(int unsigned i=0; i < d_hat.size(); i++) cout << d_hat.at(i) << "\n...\n"; cout << "\nSIMPLE SUBSTITUTION\n\n"; } //semantic action function on multiple substitution void do_mSubst(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; //cout << "\nMULTIPLE SUBSTITUTION\n\n"; } //semantic action function on unbounded choice substitution void do_mChoice(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; cout << "\nUNBOUNDED CHOICE SUBSTITUTION\n\n"; } void do_logicExpr(char const* start, char const* end) { string str(start, end); //use boost tokenizer to break down tokens typedef boost::tokenizer Tokenizer; boost::char_separator sep(" -+/*=:()<",0,boost::drop_empty_tokens); // char separator definition Tokenizer tok(str, sep); Tokenizer::iterator tok_iter = tok.begin(); //pair dependency; //create a pair object for dependencies //create a vector object to store all tokens vector dx; for(tok.begin(); tok_iter != tok.end(); ++tok_iter) //save all tokens in vector { dx.push_back(*tok_iter ); } for(unsigned int i=0; i cout << "PUSH(" << str << ')' << endl; cout << "\nPREDICATE\n\n"; } void do_predicate(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; cout << "\nMULTIPLE PREDICATE\n\n"; } void do_ifSelectPre(char const* start, char const* end) { string str(start, end); //if cout << "PUSH(" << str << ')' << endl; cout << "\nPROTECTED SUBSTITUTION\n\n"; } //semantic action function on machine substitution void do_machSubst(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; cout << "\nMACHINE SUBSTITUTION\n\n"; } } //////////////////////////////////////////////////////////////////////////// // // Machine Substitution Grammar // //////////////////////////////////////////////////////////////////////////// // Simple substitution grammar parser with integer values removed struct Substitution : public grammar { template struct definition { definition(Substitution const& ) { machine_subst = ( (simple_subst) | (multi_subst) | (if_select_pre_subst) | (unbounded_choice) )[&do_machSubst] ; unbounded_choice = str_p("ANY") ide_list str_p("WHERE") predicate str_p("THEN") machine_subst str_p("END") ; if_select_pre_subst = ( ( str_p("IF") predicate str_p("THEN") machine_subst *( str_p("ELSIF") predicate machine_subst ) !( str_p("ELSE") machine_subst) str_p("END") ) | ( str_p("SELECT") predicate str_p("THEN") machine_subst *( str_p("WHEN") predicate machine_subst ) !( str_p("ELSE") machine_subst) str_p("END")) | ( str_p("PRE") predicate str_p("THEN") machine_subst str_p("END") ) )[&do_ifSelectPre] ; multi_subst = ( (machine_subst) *( ( str_p("||") (machine_subst) ) | ( str_p("[]") (machine_subst) ) ) ) [&do_mSubst] ; simple_subst = (identifier str_p(":=") arith_expr) [&do_sSubst] ; expression = predicate | arith_expr ; predicate = ( (logic_expr) *( ( ch_p('&') (logic_expr) ) | ( str_p("OR") (logic_expr) ) ) )[&do_predicate] ; logic_expr = ( identifier (str_p("<") arith_expr) | (str_p("<") arith_expr) | (str_p("/:") arith_expr) | (str_p("<:") arith_expr) | (str_p("/<:") arith_expr) | (str_p("<<:") arith_expr) | (str_p("/<<:") arith_expr) | (str_p("<=") arith_expr) | (str_p("=") arith_expr) | (str_p("=") arith_expr) | (str_p("=") arith_expr) ) [&do_logicExpr] ; arith_expr = term *( ('+' term)[&do_add] | ('-' term)[&do_subt] ) ; term = factor ( ('' factor)[&do_mult] | ('/' factor)[&do_div] ) ; factor = lexeme_d[( identifier | +digit_p)[&do_noint]] | '(' expression ')' | ('+' factor) ; ide_list = identifier *( ch_p(',') identifier ) ; identifier = alpha_p +( alnum_p | ch_p('_') ) ; } rule machine_subst, unbounded_choice, if_select_pre_subst, multi_subst, simple_subst, expression, predicate, logic_expr, arith_expr, term, factor, ide_list, identifier; rule<ScannerT> const& start() const { return predicate; //return multi_subst; //return machine_subst; } }; }; //////////////////////////////////////////////////////////////////////////// // // Main program // //////////////////////////////////////////////////////////////////////////// int main() { cout << "*********************************\n\n"; cout << "\t\t...Machine Parser...\n\n"; cout << "*********************************\n\n"; // cout << "Type an expression...or [q or Q] to quit\n\n"; string str; int machineCount = 0; char strFilename[256]; //file name store as a string object do { cout << "Please enter a filename...or [q or Q] to quit:\n\n "; //prompt for file name to be input //char strFilename[256]; //file name store as a string object cin strFilename; if(*strFilename == 'q' || *strFilename == 'Q') //termination condition return 0; ifstream inFile(strFilename); // opens file object for reading //output file for truncated machine (operations only) if (inFile.fail()) cerr << "\nUnable to open file for reading.\n" << endl; inFile.unsetf(std::ios::skipws); Substitution elementary_subst; // Simple substitution parser object string next; while (inFile str) { getline(inFile, next); str += next; if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; parse_info< info = parse(str.c_str(), elementary_subst !end_p, space_p); if (info.full) { cout << "\n-------------------------\n"; cout << "Parsing succeeded\n"; cout << "\n-------------------------\n"; } else { cout << "\n-------------------------\n"; cout << "Parsing failed\n"; cout << "stopped at: " << info.stop << "\"\n"; cout << "\n-------------------------\n"; } } } while ( (*strFilename != 'q' || *strFilename !='Q')); return 0; } However, I am experiencing the following unexpected behaviours on testing: The text files I used are: f1.txt, ... containing ...: debt:=(LoanRequest+outstandingLoan1)*20 . f2.txt, ... containing ...: debt:=(LoanRequest+outstandingLoan1)*20 || newDebt := loanammount-paidammount || price := purchasePrice + overhead + bb . f3.txt, ... containing ...: yy < (xx+7+ww) . f4.txt, ... containing ...: yy < (xx+7+ww) & yy : NAT . When I use multi_subst as start rule both files (f1 and f2) are parsed correctly; When I use machine_subst as start rule file f1 parse correctly, while file f2 fails, producing the error: “Parsing failed stopped at: || newDebt := loanammount-paidammount || price := purchasePrice + overhead + bb” When I use predicate as start symbol, file f3 parse correctly, but file f4 yields the error: “ “Parsing failed stopped at: & yy : NAT” Can anyone help with the grammar, please? It appears there are problems with the grammar that I have so far been unable to spot.

    Read the article

  • DEV C ++ Error: expected declaration before '}' token

    - by Francesca
    What does this mean? My program goes like this: (NOTE: The line that has the error was the line coming before case 2.) case 1: { cout<< "C * H * E * M * I * S * T * R * Y \n\n"; cout<< "1) What is the valence electron configuration of Selenium (Se)?\n\n"; cout<< "\na) 1s2 2s2 2p6 3s2\n\n"; cout<< "\nb) 1s2 2s2 2p2\n\n"; cout<< "\nc)4s2 4p4\n\n"; cout<< "\nd) 1s2 2s2 2p6 3s2 3p6 4s2 3d10 4p6 5s2 4d10 5p5\n\n"; cout<< "Enter your answer:\n"; cin>> answer; if (answer == 'c') { cout<<"Your answer is correct. Please press the enter key to proceed to the next question.\n\n"; } else cout<< "The correct answer is C. Please press the enter key to proceed to the next question.\n\n"; getch (); } getch (); cout<< "2) Which element yields the biggest atomic radius?\n\n"; cout<< "\na) Ca\n\n"; cout<< "\nb) Xe\n\n"; cout<< "\nc) B\n\n"; cout<< "\nd) Cs\n\n"; cout<< "Enter your answer:\n"; cin>> answer; if (answer == 'd') { cout<< "Your answer is correct. Please press the enter key to proceed to the next question.\n\n"; } else cout<< "The correct answer is D. Please press the enter key to proceed to the next question.\n\n"; getch (); } cout<< "3) Name the ionic compound K2 Cr2 O7\n\n"; cout<< "\na) potassium chloride\n\n"; cout<< "\nb) potassium carbonate\n\n"; cout<< "\nc) potassium chromite\n\n"; cout<< "\nd) potassium chromate\n\n"; cout<< "Enter your answer:\n"; cin>> answer; if (answer == 'd') { cout<< "Your answer is correct. Please press the enter key to proceed to the next question.\n\n"; } else cout<< "The correct answer is D. Please press the enter key to proceed to the next question.\n\n"; getch (); } } case 2: { cout<< "G * E * O * M * E * T * R * Y \n\n"; The error, as noted in the title is expected declaration before '}' token at the line noted in my opening paragraph.

    Read the article

  • overloading "<<" with a struct (no class) cout style

    - by monkeyking
    I have a struct that I'd like to output using either 'std::cout' or some other output stream. Is this possible without using classes? Thanks #include <iostream> #include <fstream> template <typename T> struct point{ T x; T y; }; template <typename T> std::ostream& dump(std::ostream &o,point<T> p) const{ o<<"x: " << p.x <<"\ty: " << p.y <<std::endl; } template<typename T> std::ostream& operator << (std::ostream &o,const point<T> &a){ return dump(o,a); } int main(){ point<double> p; p.x=0.1; p.y=0.3; dump(std::cout,p); std::cout << p ;//how? return 0; } I tried different syntax' but I cant seem to make it work.

    Read the article

  • Le coût des pertes de données par les entreprises françaises a augmenté de 16% en un an, et a franchit la barre des 2,2 millions d'euros

    Le coût des pertes de données par les entreprises françaises a augmenté de 16% en un an, et a franchit la barre des 2,2 millions d'euros Symantec et le Ponemon Institute publient aujourd'hui les résultats de l'édition 2010 de l'étude sur les coûts des pertes de données en France, intitulée 2010 Annual Study: French Cost of a Data Breach. Selon cette étude, le coût des pertes de données a augmenté par rapport à celui constaté l'année dernière lors de la première édition de l'étude. Le coût moyen d'une perte de données pour les entreprises a augmenté de 16 % par rapport à 2009, s'élevant à 2,2 M €, et le coût par donnée perdue atteint 98 €, soit 9 € de plus qu'en 2009. Il ressort également de cette étude que, comme l'année dernière,...

    Read the article

  • Tuesday + 3 = Friday? C++ Programming Problem

    - by lampshade
    Looking at the main function, we can see that I've Hard Coded the "Monday" into my setDay public function. It is easy to grab a day of the week from the user using a c-string (as I did in setDay), but how would I ask the user to add n to the day that is set, "Monday" and come up with "Thursday"? It is hard because typdef enum { INVALID, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY} doesn't interpret 9 is 0 and/or 10 as 1. #include <iostream> using std::cout; using std::endl; class DayOfTheWeek //class is encapsulation of functions and members that manipulate the data. { public: DayOfTheWeek(); // Constructor virtual ~DayOfTheWeek(); // Destructor void setDay(const char * day); // Function to set the day void printDay() const; // Function to Print the day. const char * getDay() const; // Function to get the day. const char * plusOneDay(); // Next day function const char * minusOneDay(); // Previous day function const char * addDays(int addValue); // function that adds days based on parameter value private: char * day; // variable for the days of the week. }; DayOfTheWeek::DayOfTheWeek() : day(0) { // Usually I would allocate pointer member variables // Here in the construction of the Object } const char * DayOfTheWeek::getDay() const { return day; // we can get the day simply by returning it. } const char * DayOfTheWeek::minusOneDay() { if ( strcmp( day, "Monday" ) == 0) { cout << "The day before " << day << " is "; return "Sunday"; } else if ( strcmp( day, "Tuesday" ) == 0 ) { cout << "The day before " << day << " is "; return "Monday"; } else if ( strcmp( day, "Wednesday" ) == 0 ) { cout << "The day before " << day << " is "; return "Tuesday"; } else if ( strcmp( day, "Thursday" ) == 0 ) { cout << "The day before " << day << " is "; return "Wednesday"; } else if ( strcmp( day, "Friday" ) == 0 ) { cout << "The day before " << day << " is "; return "Thursday"; } else if ( strcmp( day, "Saturday" ) == 0 ) { cout << "The day before " << day << " is "; return "Friday"; } else if ( strcmp( day, "Sunday" ) == 0 ) { cout << "The day before " << day << " is "; return "Saturday"; } else { cout << "'" << day << "'"; return "is an invalid day of the week!"; } } const char * DayOfTheWeek::plusOneDay() { if ( strcmp( day, "Monday" ) == 0) { cout << "The day after " << day << " is "; return "Tuesday"; } else if ( strcmp( day, "Tuesday" ) == 0 ) { cout << "The day after " << day << " is "; return "Wednesday"; } else if ( strcmp( day, "Wednesday" ) == 0 ) { cout << "The day after " << day << " is "; return "Thursday"; } else if ( strcmp( day, "Thursday" ) == 0 ) { cout << "The day after " << day << " is "; return "Friday"; } else if ( strcmp( day, "Friday" ) == 0 ) { cout << "The day after " << day << " is "; return "Saturday"; } else if ( strcmp( day, "Saturday" ) == 0 ) { cout << "The day after " << day << " is "; return "Sunday"; } else if ( strcmp( day, "Sunday" ) == 0 ) { cout << "The day after " << day << " is "; return "Monday"; } else { cout << "'" << day << "'"; return " is an invalid day of the week!"; } } const char * DayOfTheWeek::addDays(int addValue) { if ( addValue < 0 ) { if ( strcmp( day, "Monday" ) == 0) { cout << day << " - " << -addValue << " = "; return "Friday"; } else if ( strcmp( day, "Tuesday" ) == 0 ) { cout << day << " - " << -addValue << " = "; return "Saturday"; } else if ( strcmp( day, "Wednesday" ) == 0 ) { cout << day << " - " << -addValue << " = "; return "Sunday"; } else if ( strcmp( day, "Thursday" ) == 0 ) { cout << day << " - " << -addValue << " = "; return "Monday"; } else if ( strcmp( day, "Friday" ) == 0 ) { cout << day << " - " << -addValue << " = "; return "Tuesday"; } else if ( strcmp( day, "Saturday" ) == 0 ) { cout << day << " - " << -addValue << " = "; return "Wednesday"; } else if ( strcmp( day, "Sunday" ) == 0 ) { cout << day << " - " << -addValue << " = "; return "Thursday"; } else { cout << "'" << day << "' "; return "is an invalid day of the week! "; } } else // if our parameter is greater than 0 (positive) { if ( strcmp( day, "Monday" ) == 0) { cout << day << " + " << addValue << " = "; return "Thursday"; } else if ( strcmp( day, "Tuesday" ) == 0 ) { cout << day << " + " << addValue << " = "; return "Friday"; } else if ( strcmp( day, "Wednesday" ) == 0 ) { cout << day << " + " << addValue << " = "; return "Saturday"; } else if ( strcmp( day, "Thursday" ) == 0 ) { cout << day << " + " << addValue << " = "; return "Sunday"; } else if ( strcmp( day, "Friday" ) == 0 ) { cout << day << " + " << addValue << " = "; return "Monday"; } else if ( strcmp( day, "Saturday" ) == 0 ) { cout << day << " + " << addValue << " = "; return "Tuesday"; } else if ( strcmp( day, "Sunday" ) == 0 ) { cout << day << " + " << addValue << " = "; return "Wednesday"; } else { cout << "'" << day << "' "; return "is an invalid day of the week! "; } } } void DayOfTheWeek::printDay() const { cout << "The Value of the " << day; } void DayOfTheWeek::setDay(const char * day) { if (day) {// Here I am allocating the object member char day pointer this->day = new char[strlen(day)+1]; size_t length = strlen(day)+1; // +1 for trailing null char strcpy_s(this->day , length , day); // copying c-strings } else day = NULL; // If their was a problem with the parameter 'day' } DayOfTheWeek::~DayOfTheWeek() { delete day; // Free the memory allocated in SetDay } int main() { DayOfTheWeek MondayObject; // declare an object MondayObject.setDay("Monday"); // Call our public function 'setDay' to set a day of the week MondayObject.printDay(); // Call our public function 'printDay' to print the day we set cout << " object is " << MondayObject.getDay() << endl; // Print the value of the object cout << MondayObject.plusOneDay() << endl; cout << MondayObject.minusOneDay() << endl; cout << MondayObject.addDays(3) << endl; MondayObject.printDay(); cout << " object is still " << MondayObject.getDay() << endl; // Print the value of the object cout << MondayObject.addDays(-3) << endl; return 0; }

    Read the article

  • Strange behavior of std::cout &operator<<...

    - by themoondothshine
    Hey ppl, I came across something weird today, and I was wondering if any of you here could explain what's happening... Here's a sample: #include <iostream> #include <cassert> using namespace std; #define REQUIRE_STRING(s) assert(s != 0) #define REQUIRE_STRING_LEN(s, n) assert(s != 0 || n == 0) class String { public: String(const char *str, size_t len) : __data(__construct(str, len)), __len(len) {} ~String() { __destroy(__data); } const char *toString() const { return const_cast<const char *>(__data); } String &toUpper() { REQUIRE_STRING_LEN(__data, __len); char *it = __data; while(it < __data + __len) { if(*it >= 'a' && *it <= 'z') *it -= 32; ++it; } return *this; } String &toLower() { REQUIRE_STRING_LEN(__data, __len); char *it = __data; while(it < __data + __len) { if(*it >= 'A' && *it <= 'Z') *it += 32; ++it; } return *this; } private: char *__data; size_t __len; protected: static char *__construct(const char *str, size_t len) { REQUIRE_STRING_LEN(str, len); char *data = new char[len]; std::copy(str, str + len, data); return data; } static void __destroy(char *data) { REQUIRE_STRING(data); delete[] data; } }; int main() { String s("Hello world!", __builtin_strlen("Hello world!")); cout << s.toLower().toString() << endl; cout << s.toUpper().toString() << endl; cout << s.toLower().toString() << endl << s.toUpper().toString() << endl; return 0; } Now, I had expected the output to be: hello world! HELLO WORLD! hello world! HELLO WORLD! but instead I got this: hello world! HELLO WORLD! hello world! hello world! I can't really understand why the second toUpper didn't have any effect.

    Read the article

  • C++, WCHAR[] to std::cout and comparision

    - by michal
    Hi, I need to put WCHAR[] to std::cout ... It is a part of PWLAN_CONNECTION_NOTIFICATION_DATA passed from Native Wifi API callback. I tried simply std::cout << var; but it prints out the numeric address of first char. the comparision (var == L"some text") doesn't work either. The debugger returns the expected value, however the comparision returns 0. How can I convert this array to a standard string(std::string)? Thanks in advance

    Read the article

  • Visual Studio C++ list iterator not decementable

    - by user69514
    I keep getting an error on visual studio that says list iterator not decrementable: line 256 My program works fine on Linux, but visual studio compiler throws this error. Dammit this is why I hate windows. Why can't the world run on Linux? Anyway, do you see what my problem is? #include <iostream> #include <fstream> #include <sstream> #include <list> using namespace std; int main(){ /** create the list **/ list<int> l; /** create input stream to read file **/ ifstream inputstream("numbers.txt"); /** read the numbers and add them to list **/ if( inputstream.is_open() ){ string line; istringstream instream; while( getline(inputstream, line) ){ instream.clear(); instream.str(line); /** get he five int's **/ int one, two, three, four, five; instream >> one >> two >> three >> four >> five; /** add them to the list **/ l.push_back(one); l.push_back(two); l.push_back(three); l.push_back(four); l.push_back(five); }//end while loop }//end if /** close the stream **/ inputstream.close(); /** display the list **/ cout << "List Read:" << endl; list<int>::iterator i; for( i=l.begin(); i != l.end(); ++i){ cout << *i << " "; } cout << endl << endl; /** now sort the list **/ l.sort(); /** display the list **/ cout << "Sorted List (head to tail):" << endl; for( i=l.begin(); i != l.end(); ++i){ cout << *i << " "; } cout << endl; list<int> lReversed; for(i=l.begin(); i != l.end(); ++i){ lReversed.push_front(*i); } cout << "Sorted List (tail to head):" << endl; for(i=lReversed.begin(); i!=lReversed.end(); ++i){ cout << *i << " "; } cout << endl << endl; /** remove first biggest element and display **/ l.pop_back(); cout << "List after removing first biggest element:" << endl; cout << "Sorted List (head to tail):" << endl; for( i=l.begin(); i != l.end(); ++i){ cout << *i << " "; } cout << endl; cout << "Sorted List (tail to head):" << endl; lReversed.pop_front(); for(i=lReversed.begin(); i!=lReversed.end(); ++i){ cout << *i << " "; } cout << endl << endl; /** remove second biggest element and display **/ l.pop_back(); cout << "List after removing second biggest element:" << endl; cout << "Sorted List (head to tail):" << endl; for( i=l.begin(); i != l.end(); ++i){ cout << *i << " "; } cout << endl; lReversed.pop_front(); cout << "Sorted List (tail to head):" << endl; for(i=lReversed.begin(); i!=lReversed.end(); ++i){ cout << *i << " "; } cout << endl << endl; /** remove third biggest element and display **/ l.pop_back(); cout << "List after removing third biggest element:" << endl; cout << "Sorted List (head to tail):" << endl; for( i=l.begin(); i != l.end(); ++i){ cout << *i << " "; } cout << endl; cout << "Sorted List (tail to head):" << endl; lReversed.pop_front(); for(i=lReversed.begin(); i!=lReversed.end(); ++i){ cout << *i << " "; } cout << endl << endl; /** create frequency table **/ const int biggest = 1000; //create array size of biggest element int arr[biggest]; //set everything to zero for(int j=0; j<biggest+1; j++){ arr[j] = 0; } //now update number of occurences for( i=l.begin(); i != l.end(); i++){ arr[*i]++; } //now print the frequency table. only print where occurences greater than zero cout << "Final list frequency table: " << endl; for(int j=0; j<biggest+1; j++){ if( arr[j] > 0 ){ cout << j << ": " << arr[j] << " occurences" << endl; } } return 0; }//end main

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >