Search Results

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

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

  • C++ Unions bit fields task

    - by learningtolive
    Can somebody clear me out why would I use union and with what purpose the same address for the cin'ed variable and bit field (task from the Schildts C++ book)? In other words why would I use union for : char ch; struct byte bit; // Display the ASCII code in binary for characters. #include <iostream> #include <conio.h> using namespace std; // a bit field that will be decoded struct byte { unsigned a : 1; unsigned b : 1; unsigned c : 1; unsigned d : 1; unsigned e : 1; unsigned f : 1; unsigned g : 1; unsigned h : 1; }; union bits { char ch; struct byte bit; } ascii ; void disp_bits(bits b); int main() { do { cin >> ascii.ch; cout << ": "; disp_bits(ascii); } while(ascii.ch!='q'); // quit if q typed return 0; } // Display the bit pattern for each character. void disp_bits(bits b) { if(b.bit.h) cout << "1 "; else cout << "0 "; if(b.bit.g) cout << "1 "; else cout << "0 "; if(b.bit.f) cout << "1 "; else cout << "0 "; if(b.bit.e) cout << "1 "; else cout << "0 "; if(b.bit.d) cout << "1 "; else cout << "0 "; if(b.bit.c) cout << "1 "; else cout << "0 "; if(b.bit.b) cout << "1 "; else cout << "0 "; if(b.bit.a) cout << "1 "; else cout << "0 "; cout << "\n"; }

    Read the article

  • Link List Problem,

    - by david
    OK i have a problem with a Link List program i'm trying to Do, the link List is working fine. Here is my code #include <iostream> using namespace std; struct record { string word; struct record * link; }; typedef struct record node; node * insert_Node( node * head, node * previous, string key ); node * search( node *head, string key, int *found); void displayList(node *head); node * delete_node( node *head, node * previous, string key); int main() { node * previous, * head = NULL; int found = 0; string node1Data,newNodeData, nextData,lastData; //set up first node cout <<"Depature"<<endl; cin >>node1Data; previous = search( head, node1Data, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, node1Data); cout <<"Depature inserted"<<endl; //insert node between first node and head cout <<"Destination"<<endl; cin >>newNodeData; previous = search( head, newNodeData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, newNodeData); cout <<"Destinationinserted"<<endl; //insert node between second node and head cout <<"Cost"<<endl; cin >>newNodeData; previous = search( head, newNodeData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, newNodeData); cout <<"Cost inserted"<<endl; cout <<"Number of Seats Required"<<endl; //place node between new node and first node cin >>nextData; previous = search( head, nextData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, nextData); cout <<"Number of Seats Required inserted"<<endl; //insert node between first node and head cout <<"Name"<<endl; cin >>newNodeData; previous = search( head, newNodeData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, newNodeData); cout <<"Name inserted"<<endl; //insert node between node and head cout <<"Address "<<endl; cin >>newNodeData; previous = search( head, newNodeData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, newNodeData); cout <<"Address inserted"<<endl; //place node as very last node cin >>lastData; previous = search( head, lastData, &found); cout <<"Previous" <<previous<<endl; head = insert_Node(head, previous, lastData); cout <<"C"<<endl; displayList(head); char Ans = 'y'; //Delete nodes do { cout <<"Enter Keyword to be delete"<<endl; cin >>nextData; previous = search( head, nextData, &found); if (found == 1) head = delete_node( head, previous,nextData); displayList(head); cout <<"Do you want to Delete more y /n "<<endl; cin >> Ans; } while( Ans =='y'); int choice, i=0, counter=0; int fclass[10]; int coach[10]; printf("Welcome to the booking program"); printf("\n-----------------"); do{ printf("\n Please pick one of the following option:"); printf("\n 1) Reserve a first class seat on Flight 101."); printf("\n 2) Reserve a coach seat on Flight 101."); printf("\n 3) Quit "); printf("\n ---------------------------------------------------------------------"); printf("\nYour choice?"); scanf("%d",&choice); switch(choice) { case 1: i++; if (i <10){ printf("Here is your seat: %d " , fclass[i]); } else if (i = 10) { printf("Sorry there is no more seats on First Class. Please wait for the next flight"); } break; case 2: if (i <10){ printf("Here is your Seat Coach: %d " , coach[i]); } else if ( i = 10) { printf("Sorry their is no more Seats on Coach. Please wait for the next flight"); } break; case 3: printf("Thank you and goodbye\n"); //exit(0); } } while (choice != 3); } /******************************************************* search function to return previous position of node ******************************************************/ node * search( node *head, string key, int *found) { node * previous, * current; current = head; previous = current; *found = 0;//not found //if (current->word < key) move through links until the next link //matches or current_word > key while( current !=NULL) { //compare exactly if (key ==current->word ) { *found = 1; break; } //if key is less than word else if ( key < current->word ) break; else { //previous stays one link behind current previous = current; current = previous -> link; } } return previous; } /******************************************************** display function as used with createList ******************************************************/ void displayList(node *head) { node * current; //current now contains the address held of the 1st node similar //to head current = head; cout << "\n\n"; if( current ==NULL) cout << "Empty List\n\n"; else { /*Keep going displaying the contents of the list and set current to the address of the next node. When set to null, there are no more nodes */ while(current !=NULL) { cout << current->word<<endl; current = current ->link; } } } /************************************************************ insert node used to position node (i) empty list head = NULL (ii) to position node before the first node key < head->word (iii) every other position including the end of the list This is done using the following steps (a) Pass in all the details to create the node either details or a whole record (b) Pass the details over to fill the node (C) Use the if statement to add the node to the list **********************************************************/ node * insert_Node( node * head, node * previous, string key ) { node * new_node, * temp; new_node = new node; //create the node new_node ->word = key; new_node -> link = NULL; if (head == NULL || key < head->word ) //empty list { //give address of head to temp temp = head; //head now points to the new_node head = new_node; //new_node now points to what head was pointing at new_node -> link = temp; } else { //pass address held in link to temp temp = previous-> link; //put address of new node to link of previous previous -> link = new_node; //pass address of temp to link of new node new_node -> link = temp; } return head; } node * delete_node( node *head, node * previous, string key) { /* this function will delete a node but will not return its contents */ node * temp; if(key == head->word) //delete node at head of list { temp = head; //point head at the next node head = head -> link; } else { //holds the address of the node after the one // to be deleted temp = previous-> link; /*assign the previous to the address of the present node to be deleted which holds the address of the next node */ previous-> link = previous-> link-> link; } delete temp; return head; }//end delete The problem i have is when i Enter in the Number 2 in the Node(Seats) i like to get a Counter Taken 2 off of 50, some thing like what i have here enter code here int choice, i=0, counter=0; int fclass[10]; int coach[10]; printf("Welcome to the booking program"); printf("\n-----------------"); do{ printf("\n Please pick one of the following option:"); printf("\n 1) Reserve a first class seat on Flight 101."); printf("\n 2) Reserve a coach seat on Flight 101."); printf("\n 3) Quit "); printf("\n ---------------------------------------------------------------------"); printf("\nYour choice?"); scanf("%d",&choice); switch(choice) { case 1: i++; if (i <10){ printf("Here is your seat: %d " , fclass[i]); } else if (i = 10) { printf("Sorry there is no more seats on First Class. Please wait for the next flight"); } break; case 2: if (i <10){ printf("Here is your Seat Coach: %d " , coach[i]); } else if ( i = 10) { printf("Sorry their is no more Seats on Coach. Please wait for the next flight"); } break; case 3: printf("Thank you and goodbye\n"); //exit(0); } } while (choice != 3); How can i get what the User enters into number of Seats into this function

    Read the article

  • compile time if && return string reference optimization

    - by Truncheon
    Hi. I'm writing a series classes that inherit from a base class using virtual. They are INT, FLOAT and STRING objects that I want to use in a scripting language. I'm trying to implement weak typing, but I don't want STRING objects to return copies of themselves when used in the following way (instead I would prefer to have a reference returned which can be used in copying): a = "hello "; b = "world"; c = a + b; I have written the following code as a mock example: #include <iostream> #include <string> #include <cstdio> #include <cstdlib> std::string dummy("<int object cannot return string reference>"); struct BaseImpl { virtual bool is_string() = 0; virtual int get_int() = 0; virtual std::string get_string_copy() = 0; virtual std::string const& get_string_ref() = 0; }; struct INT : BaseImpl { int value; INT(int i = 0) : value(i) { std::cout << "constructor called\n"; } INT(BaseImpl& that) : value(that.get_int()) { std::cout << "copy constructor called\n"; } bool is_string() { return false; } int get_int() { return value; } std::string get_string_copy() { char buf[33]; sprintf(buf, "%i", value); return buf; } std::string const& get_string_ref() { return dummy; } }; struct STRING : BaseImpl { std::string value; STRING(std::string s = "") : value(s) { std::cout << "constructor called\n"; } STRING(BaseImpl& that) { if (that.is_string()) value = that.get_string_ref(); else value = that.get_string_copy(); std::cout << "copy constructor called\n"; } bool is_string() { return true; } int get_int() { return atoi(value.c_str()); } std::string get_string_copy() { return value; } std::string const& get_string_ref() { return value; } }; struct Base { BaseImpl* impl; Base(BaseImpl* p = 0) : impl(p) {} ~Base() { delete impl; } }; int main() { Base b1(new INT(1)); Base b2(new STRING("Hello world")); Base b3(new INT(*b1.impl)); Base b4(new STRING(*b2.impl)); std::cout << "\n"; std::cout << b1.impl->get_int() << "\n"; std::cout << b2.impl->get_int() << "\n"; std::cout << b3.impl->get_int() << "\n"; std::cout << b4.impl->get_int() << "\n"; std::cout << "\n"; std::cout << b1.impl->get_string_ref() << "\n"; std::cout << b2.impl->get_string_ref() << "\n"; std::cout << b3.impl->get_string_ref() << "\n"; std::cout << b4.impl->get_string_ref() << "\n"; std::cout << "\n"; std::cout << b1.impl->get_string_copy() << "\n"; std::cout << b2.impl->get_string_copy() << "\n"; std::cout << b3.impl->get_string_copy() << "\n"; std::cout << b4.impl->get_string_copy() << "\n"; return 0; } It was necessary to add an if check in the STRING class to determine whether its safe to request a reference instead of a copy: Script code: a = "test"; b = a; c = 1; d = "" + c; /* not safe to request reference by standard */ C++ code: STRING(BaseImpl& that) { if (that.is_string()) value = that.get_string_ref(); else value = that.get_string_copy(); std::cout << "copy constructor called\n"; } If was hoping there's a way of moving that if check into compile time, rather than run time.

    Read the article

  • how to avoid temporaries when copying weakly typed object

    - by Truncheon
    Hi. I'm writing a series classes that inherit from a base class using virtual. They are INT, FLOAT and STRING objects that I want to use in a scripting language. I'm trying to implement weak typing, but I don't want STRING objects to return copies of themselves when used in the following way (instead I would prefer to have a reference returned which can be used in copying): a = "hello "; b = "world"; c = a + b; I have written the following code as a mock example: #include <iostream> #include <string> #include <cstdio> #include <cstdlib> std::string dummy("<int object cannot return string reference>"); struct BaseImpl { virtual bool is_string() = 0; virtual int get_int() = 0; virtual std::string get_string_copy() = 0; virtual std::string const& get_string_ref() = 0; }; struct INT : BaseImpl { int value; INT(int i = 0) : value(i) { std::cout << "constructor called\n"; } INT(BaseImpl& that) : value(that.get_int()) { std::cout << "copy constructor called\n"; } bool is_string() { return false; } int get_int() { return value; } std::string get_string_copy() { char buf[33]; sprintf(buf, "%i", value); return buf; } std::string const& get_string_ref() { return dummy; } }; struct STRING : BaseImpl { std::string value; STRING(std::string s = "") : value(s) { std::cout << "constructor called\n"; } STRING(BaseImpl& that) { if (that.is_string()) value = that.get_string_ref(); else value = that.get_string_copy(); std::cout << "copy constructor called\n"; } bool is_string() { return true; } int get_int() { return atoi(value.c_str()); } std::string get_string_copy() { return value; } std::string const& get_string_ref() { return value; } }; struct Base { BaseImpl* impl; Base(BaseImpl* p = 0) : impl(p) {} ~Base() { delete impl; } }; int main() { Base b1(new INT(1)); Base b2(new STRING("Hello world")); Base b3(new INT(*b1.impl)); Base b4(new STRING(*b2.impl)); std::cout << "\n"; std::cout << b1.impl->get_int() << "\n"; std::cout << b2.impl->get_int() << "\n"; std::cout << b3.impl->get_int() << "\n"; std::cout << b4.impl->get_int() << "\n"; std::cout << "\n"; std::cout << b1.impl->get_string_ref() << "\n"; std::cout << b2.impl->get_string_ref() << "\n"; std::cout << b3.impl->get_string_ref() << "\n"; std::cout << b4.impl->get_string_ref() << "\n"; std::cout << "\n"; std::cout << b1.impl->get_string_copy() << "\n"; std::cout << b2.impl->get_string_copy() << "\n"; std::cout << b3.impl->get_string_copy() << "\n"; std::cout << b4.impl->get_string_copy() << "\n"; return 0; } It was necessary to add an if check in the STRING class to determine whether its safe to request a reference instead of a copy: Script code: a = "test"; b = a; c = 1; d = "" + c; /* not safe to request reference by standard */ C++ code: STRING(BaseImpl& that) { if (that.is_string()) value = that.get_string_ref(); else value = that.get_string_copy(); std::cout << "copy constructor called\n"; } If was hoping there's a way of moving that if check into compile time, rather than run time.

    Read the article

  • C++ STL: How to write wrappers for cout, cerr, cin and endl?

    - by Ashwin
    I do not like using namespace std, but I am also tired of having to type std:: in front of every cout, cin, cerr and endl. So, I thought of giving them shorter new names like this: // STLWrapper.h #include <iostream> #include <string> extern std::ostream& Cout; extern std::ostream& Cerr; extern std::istream& Cin; extern std::string& Endl; // STLWrapper.cpp #include "STLWrapper.h" std::ostream& Cout = std::cout; std::ostream& Cerr = std::cerr; std::istream& Cerr = std::cin; std::string _EndlStr("\n"); std::string& Endl = _EndlStr; This works. But, are there any problems in the above which I am missing? Is there a better way to achieve the same?

    Read the article

  • Accessing a vector<vector<int>> as a flat array

    - by user1762276
    For this array: vector<vector<int> > v; v.push_back(vector<int>(0)); v.back().push_back(1); v.back().push_back(2); v.back().push_back(3); v.back().push_back(4); I can output {1, 2, 3, 4} easily enough: cout << v[0][0] << endl; cout << v[0][1] << endl; cout << v[0][2] << endl; cout << v[0][3] << endl; To access it as a flat array I can do this: int* z = (int*)&v[0].front(); cout << z[0] << endl; cout << z[1] << endl; cout << z[2] << endl; cout << z[3] << endl; Now, how do I access the multidimensional vector as a flat multidimensional array? I cannot use the same format as accessing a single-dimensional vector: // This does not work (outputs garbage) int** n = (int**)&v.front(); cout << n[0][0] << endl; cout << n[0][1] << endl; cout << n[0][2] << endl; cout << n[0][3] << endl; The workaround I've found is to do this: int** n = new int* [v.size()]; for (size_t i = 0; i < v.size(); i++) { n[i] = &v.at(i).front(); } cout << n[0][0] << endl; cout << n[0][1] << endl; cout << n[0][2] << endl; cout << n[0][3] << endl; Is there a way to access the entire multidimensional vector like a flat c-style array without having to dynamically allocate each dimension above the data before accessing it? Speed is not critical in the implementation and clarity for maintenance is paramount. A multidimensional vector is just fine for storing the data. However, I want to also expose the data as a flat c-style array in the SDK so that it can be easily accessible by other languages. This means that exposing the vectors as an STL object is a no go. The solution I came up with works fine for my needs as I only evaluate the array once at the very end of processing to "flatten" it. However, is there a better way to go about this? Or am I already doing it the best way I possibly can without re-implementing my own data structure (overkill since my flatten code is only a few lines). Thank you for your advice, friends!

    Read the article

  • Error codes for C++

    - by billy
    #include <iostream> #include <iomanip> using namespace std; //Global constant variable declaration const int MaxRows = 8, MaxCols = 10, SEED = 10325; //Functions Declaration void PrintNameHeader(ostream& out); void Fill2DArray(double ary[][MaxCols]); void Print2DArray(const double ary[][MaxCols]); double GetTotal(const double ary[][MaxCols]); double GetAverage(const double ary[][MaxCols]); double GetRowTotal(const double ary[][MaxCols], int theRow); double GetColumnTotal(const double ary[][MaxCols], int theRow); double GetHighestInRow(const double ary[][MaxCols], int theRow); double GetLowestInRow(const double ary[][MaxCols], int theRow); double GetHighestInCol(const double ary[][MaxCols], int theCol); double GetLowestInCol(const double ary[][MaxCols], int theCol); double GetHighest(const double ary[][MaxCols], int& theRow, int& theCol); double GetLowest(const double ary[][MaxCols], int& theRow, int& theCol); int main() { int theRow; int theCol; PrintNameHeader(cout); cout << fixed << showpoint << setprecision(1); srand(static_cast<unsigned int>(SEED)); double ary[MaxRows][MaxCols]; cout << "The seed value for random number generator is: " << SEED << endl; cout << endl; Fill2DArray(ary); Print2DArray(ary); cout << " The Total for all the elements in this array is: " << setw(7) << GetTotal(ary) << endl; cout << "The Average of all the elements in this array is: " << setw(7) << GetAverage(ary) << endl; cout << endl; cout << "The sum of each row is:" << endl; for(int index = 0; index < MaxRows; index++) { cout << "Row " << (index + 1) << ": " << GetRowTotal(ary, theRow) << endl; } cout << "The highest and lowest of each row is: " << endl; for(int index = 0; index < MaxCols; index++) { cout << "Row " << (index + 1) << ": " << GetHighestInRow(ary, theRow) << " " << GetLowestInRow(ary, theRow) << endl; } cout << "The highest and lowest of each column is: " << endl; for(int index = 0; index < MaxCols; index++) { cout << "Col " << (index + 1) << ": " << GetHighestInCol(ary, theRow) << " " << GetLowestInCol(ary, theRow) << endl; } cout << "The highest value in all the elements in this array is: " << endl; cout << GetHighest(ary, theRow, theCol) << "[" << theRow << "]" << "[" << theCol << "]" << endl; cout << "The lowest value in all the elements in this array is: " << endl; cout << GetLowest(ary, theRow, theCol) << "[" << theRow << "]" << "[" << theCol << "]" << endl; return 0; } //Define Functions void PrintNameHeader(ostream& out) { out << "*******************************" << endl; out << "* *" << endl; out << "* C.S M10A Spring 2010 *" << endl; out << "* Programming Assignment 10 *" << endl; out << "* Due Date: Thurs. Mar. 25 *" << endl; out << "*******************************" << endl; out << endl; } void Fill2DArray(double ary[][MaxCols]) { for(int index1 = 0; index1 < MaxRows; index1++) { for(int index2= 0; index2 < MaxCols; index2++) { ary[index1][index2] = (rand()%1000)/10; } } } void Print2DArray(const double ary[][MaxCols]) { cout << " Column "; for(int index = 0; index < MaxCols; index++) { int column = index + 1; cout << " " << column << " "; } cout << endl; cout << " "; for(int index = 0; index < MaxCols; index++) { int column = index +1; cout << "----- "; } cout << endl; for(int index1 = 0; index1 < MaxRows; index1++) { cout << "Row " << (index1 + 1) << ":"; for(int index2= 0; index2 < MaxCols; index2++) { cout << setw(6) << ary[index1][index2]; } } } double GetTotal(const double ary[][MaxCols]) { double total = 0; for(int theRow = 0; theRow < MaxRows; theRow++) { total = total + GetRowTotal(ary, theRow); } return total; } double GetAverage(const double ary[][MaxCols]) { double total = 0, average = 0; total = GetTotal(ary); average = total / (MaxRows * MaxCols); return average; } double GetRowTotal(const double ary[][MaxCols], int theRow) { double sum = 0; for(int index = 0; index < MaxCols; index++) { sum = sum + ary[theRow][index]; } return sum; } double GetColumTotal(const double ary[][MaxCols], int theCol) { double sum = 0; for(int index = 0; index < theCol; index++) { sum = sum + ary[index][theCol]; } return sum; } double GetHighestInRow(const double ary[][MaxCols], int theRow) { double highest = 0; for(int index = 0; index < MaxCols; index++) { if(ary[theRow][index] > highest) highest = ary[theRow][index]; } return highest; } double GetLowestInRow(const double ary[][MaxCols], int theRow) { double lowest = 0; for(int index = 0; index < MaxCols; index++) { if(ary[theRow][index] < lowest) lowest = ary[theRow][index]; } return lowest; } double GetHighestInCol(const double ary[][MaxCols], int theCol) { double highest = 0; for(int index = 0; index < MaxRows; index++) { if(ary[index][theCol] > highest) highest = ary[index][theCol]; } return highest; } double GetLowestInCol(const double ary[][MaxCols], int theCol) { double lowest = 0; for(int index = 0; index < MaxRows; index++) { if(ary[index][theCol] < lowest) lowest = ary[index][theCol]; } return lowest; } double GetHighest(const double ary[][MaxCols], int& theRow, int& theCol) { theRow = 0; theCol = 0; double highest = ary[theRow][theCol]; for(int index = 0; index < MaxRows; index++) { for(int index1 = 0; index1 < MaxCols; index1++) { double highest = 0; if(ary[index1][theCol] > highest) { highest = ary[index][index1]; theRow = index; theCol = index1; } } } return highest; } double Getlowest(const double ary[][MaxCols], int& theRow, int& theCol) { theRow = 0; theCol = 0; double lowest = ary[theRow][theCol]; for(int index = 0; index < MaxRows; index++) { for(int index1 = 0; index1 < MaxCols; index1++) { double lowest = 0; if(ary[index1][theCol] < lowest) { lowest = ary[index][index1]; theRow = index; theCol = index1; } } } return lowest; } . 1>------ Build started: Project: teddy lab 10, Configuration: Debug Win32 ------ 1>Compiling... 1>lab 10.cpp 1>c:\users\owner\documents\visual studio 2008\projects\teddy lab 10\teddy lab 10\ lab 10.cpp(46) : warning C4700: uninitialized local variable 'theRow' used 1>c:\users\owner\documents\visual studio 2008\projects\teddy lab 10\teddy lab 10\ lab 10.cpp(62) : warning C4700: uninitialized local variable 'theCol' used 1>Linking... 1> lab 10.obj : error LNK2028: unresolved token (0A0002E0) "double __cdecl GetLowest(double const (* const)[10],int &,int &)" (?GetLowest@@$$FYANQAY09$$CBNAAH1@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ) 1> lab 10.obj : error LNK2019: unresolved external symbol "double __cdecl GetLowest(double const (* const)[10],int &,int &)" (?GetLowest@@$$FYANQAY09$$CBNAAH1@Z) referenced in function "int __cdecl main(void)" (?main@@$$HYAHXZ) 1>C:\Users\owner\Documents\Visual Studio 2008\Projects\ lab 10\Debug\ lab 10.exe : fatal error LNK1120: 2 unresolved externals 1>Build log was saved at "file://c:\Users\owner\Documents\Visual Studio 2008\Projects\ lab 10\teddy lab 10\Debug\BuildLog.htm" 1>teddy lab 10 - 3 error(s), 2 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    Read the article

  • getline won't let me type, c++

    - by Stijn
    I try to get the name of a game the users chooses and store it in a vector. I use getline so the user can use a space. When I try to type a new game to add it won't let me. It automaticly displays me games library. Please tell me what I do wrong. Problem is at if(action == "add") Here's my code: #include <iostream> #include <string> #include <vector> #include <algorithm> #include <ctime> #include <cstdlib> using namespace std; int main() { vector<string>::const_iterator myIterator; vector<string>::const_iterator iter; vector<string> games; games.push_back("Crysis 2"); games.push_back("GodOfWar 3"); games.push_back("FIFA 12"); cout <<"Welcome to your Games Library.\n"; cout <<"\nThese are your games:\n"; for (iter = games.begin(); iter != games.end(); ++iter) { cout <<*iter <<endl; } //the loop! string action; string newGame; cout <<"\n-Type 'exit' if you want to quit.\n-Type 'add' if you want to add a game.\n-Type 'delete' if you want to delete a game.\n-Type 'find' if you want to search a game.\n-Type 'game' if you don't know what game to play.\n-Type 'show' if you want to view your library."; while (action != "exit") { cout <<"\n\nWhat do you want to do: "; cin >> action; //problem is here if (action == "add") { cout <<"\nType the name of the game you want to add: "; getline (cin, newGame); games.push_back(newGame); for (iter = games.begin(); iter != games.end(); ++iter) { cout <<*iter <<endl; } continue; } else if (action == "show") { cout <<"\nThese are your games:\n"; for (iter = games.begin(); iter != games.end(); ++iter) { cout <<*iter <<endl; } } else if (action == "delete") { cout <<"Type the name of the game you want to delete: "; cin >> newGame; getline (cin, newGame); iter = find(games.begin(), games.end(), newGame); if(iter != games.end()) { games.erase(iter); cout <<"\nGame deleted!"; } else { cout<<"\nGame not found."; } continue; } else if (action == "find") { cout <<"Which game you want to look for in your library: "; cin >> newGame; getline (cin, newGame); iter = find(games.begin(), games.end(), newGame); if (iter != games.end()) { cout << "Game found.\n"; } else { cout << "Game not found.\n"; } continue; } else if (action == "game") { srand(static_cast<unsigned int>(time(0))); random_shuffle(games.begin(), games.end()); cout << "\nWhy don't you play " << games[0]; continue; } else if (action == "quit") { cout <<"\nRemember to have fun while gaming!!\n"; break; } else { cout <<"\nCommand not found"; } } return 0; }

    Read the article

  • three out of five file streams wont open, i believe its a problem with my ifstreams.

    - by user320950
    #include<iostream> #include<fstream> #include<cstdlib> #include<iomanip> using namespace std; int main() { ifstream in_stream; // reads itemlist.txt ofstream out_stream1; // writes in items.txt ifstream in_stream2; // reads pricelist.txt ofstream out_stream3;// writes in plist.txt ifstream in_stream4;// read recipt.txt ofstream out_stream5;// write display.txt int wrong=0; in_stream.open("ITEMLIST.txt", ios::in); // list of avaliable items if( in_stream.fail() )// check to see if itemlist.txt is open { wrong++; cout << " the error occured here0, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n" << endl; exit(1); } else{ cout << " System ran correctly " << endl; out_stream1.open("ITEMLIST.txt", ios::out); // list of avaliable items if(out_stream1.fail() )// check to see if itemlist.txt is open { wrong++; cout << " the error occured here1, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n"; exit(1); } else{ cout << " System ran correctly " << endl; } in_stream2.open("PRICELIST.txt", ios::in); if( in_stream2.fail() ) { wrong++; cout << " the error occured here2, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n"; exit (1); } else{ cout << " System ran correctly " << endl; } out_stream3.open("PRICELIST.txt", ios::out); if(out_stream3.fail() ) { wrong++; cout << " the error occured here3, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n"; exit (1); } else{ cout << " System ran correctly " << endl; } in_stream4.open("display.txt", ios::in); if( in_stream4.fail() ) { wrong++; cout << " the error occured here4, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n"; exit (1); } else{ cout << " System ran correctly " << endl; } out_stream5.open("display.txt", ios::out); if( out_stream5.fail() ) { wrong++; cout << " the error occured here5, you have " << wrong++ << " errors" << endl; cout << "Error opening the file\n"; exit (1); } else{ cout << " System ran correctly " << endl; }

    Read the article

  • Invalid function declaration. DevC++

    - by user69514
    Why do I get invalid function declaration when I compile the code in DevC++ in Windows, but when I compile it in CodeBlocks on Linux it works fine. #include <iostream> #include <vector> using namespace std; //structure to hold item information struct item{ string name; double price; }; //define sandwich, chips, and drink struct item sandwich{"Sandwich", 3.00}; **** error is here ***** struct item chips{"Chips", 1.50}; **** error is here ***** struct item drink{"Large Drink", 2.00}; **** error is here ***** vector<item> cart; //vector to hold the items double total = 0.0; //total const double tax = 0.0825; //tax //gets item choice from user char getChoice(){ cout << "Select an item:" << endl; cout << "S: Sandwich. $3.00" << endl; cout << "C: Chips. $1.50" << endl; cout << "D: Drink. $2.00" << endl; cout << "X: Cancel. Start over" << endl; cout << "T: Total" << endl; char choice; cin >> choice; return choice; } //displays current items in cart and total void displayCart(){ cout << "\nCart:" << endl; for(unsigned int i=0; i<cart.size(); i++){ cout << cart.at(i).name << ". $" << cart.at(i).price << endl; } cout << "Total: $" << total << endl << endl; } //adds item to the cart void addItem(struct item bought){ cart.push_back(bought); total += bought.price; displayCart(); } //displays the receipt, items, prices, subtotal, taxes, and total void displayReceipt(){ cout << "\nReceipt:" << endl; cout << "Items: " << cart.size() << endl; for(unsigned int i=0; i<cart.size(); i++){ cout << (i+1) << ". " << cart.at(i).name << ". $" << cart.at(i).price << endl; } cout << "----------------------------" << endl; cout << "Subtotal: $" << total << endl; double taxes = total*tax; cout << "Tax: $" << taxes << endl; cout << "Total: $" << (total + taxes) << endl; } int main(){ //sentinel to stop the loop bool stop = false; char choice; while (stop == false ){ choice = getChoice(); //add sandwich if( choice == 's' || choice == 'S' ){ addItem(sandwich); } //add chips else if( choice == 'c' || choice == 'C' ){ addItem(chips); } //add drink else if( choice == 'd' || choice == 'D' ){ addItem(drink); } //remove everything from cart else if( choice == 'x' || choice == 'X' ){ cart.clear(); total = 0.0; cout << "\n***** Transcation Canceled *****\n" << endl; } //calcualte total else if( choice == 't' || choice == 'T' ){ displayReceipt(); stop = true; } //or wront item picked else{ cout << choice << " is not a valid choice. Try again\n" << endl; } }//end while loop return 0; //end of program }

    Read the article

  • problem with piping in my own implementation of shell

    - by codemax
    Hey guys, i am implementing my own shell. I want to involve piping. i searched here and i got a code. But it is not working.Can any one help me? this is my code #include <sys/types.h> #include <sys/wait.h> #include <sys/ipc.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <iostream> #include <cstdlib> using namespace std; char temp1[81][81],temp2[81][81] ,*cmdptr1[40], *cmdptr2[40]; void process(char**,int); int arg_count, count; int arg_cnt[2]; int pip,tok; char input[81]; int fds[2]; void process( char* cmd[])//, int arg_count ) { pid_t pid; pid = fork(); //char path[81]; //getcwd(path,81); //strcat(path,"/"); //strcat(path,cmd[0]); if(pid < 0) { cout << "Fork Failed" << endl; exit(-1); } else if( pid == 0 ) { execvp( cmd[0] , cmd ); } else { wait(NULL); } } void pipe(char **cmd1, char**cmd2) { cout<<endl<<endl<<"in pipe"<<endl; for(int i=0 ; i<arg_cnt[0] ; i++) { cout<<cmdptr1[i]<<" "; } cout<<endl; for(int i=0 ; i<arg_cnt[1] ; i++) { cout<<cmdptr2[i]<<" "; } pipe(fds); if (fork() == 0 ) { dup2(fds[1], 1); close(fds[0]); close(fds[1]); process(cmd1); } if (fork() == 0) { dup2(fds[0], 0); close(fds[0]); close(fds[1]); process(cmd2); } close(fds[0]); close(fds[1]); wait(NULL); } void pipecommand(char** cmd1, char** cmd2) { cout<<endl<<endl; for(int i=0 ; i<arg_cnt[0] ; i++) { cout<<cmd1[i]<<" "; } cout<<endl; for(int i=0 ; i<arg_cnt[1] ; i++) { cout<<cmd2[i]<<" "; } int fds[2]; // file descriptors pipe(fds); // child process #1 if (fork() == 0) { // Reassign stdin to fds[0] end of pipe. dup2(fds[0], STDIN_FILENO); close(fds[1]); close(fds[0]); process(cmd2); // child process #2 if (fork() == 0) { // Reassign stdout to fds[1] end of pipe. dup2(fds[1], STDOUT_FILENO); close(fds[0]); close(fds[1]); // Execute the first command. process(cmd1); } wait(NULL); } close(fds[1]); close(fds[0]); wait(NULL); } void splitcommand1() { tok++; int k,done=0,no=0; arg_count = 0; for(int i=count ; input[i] != '\0' ; i++) { k=0; while(1) { count++; if(input[i] == ' ') { break; } if((input[i] == '\0')) { done = 1; break; } if(input[i] == '|') { pip = 1; done = 1; break; } temp1[arg_count][k++] = input[i++]; } temp1[arg_count][k++] = '\0'; arg_count++; if(done == 1) { break; } } for(int i=0 ; i<arg_count ; i++) { cmdptr1[i] = temp1[i]; } arg_cnt[tok] = arg_count; } void splitcommand2() { tok++; cout<<"count is :"<<count<<endl; int k,done=0,no=0; arg_count = 0; for(int i=count ; input[i] != '\0' ; i++) { k=0; while(1) { count++; if(input[i] == ' ') { break; } if((input[i] == '\0')) { done = 1; break; } if(input[i] == '|') { pip = 1; done = 1; cout<<"PIP"; break; } temp2[arg_count][k++] = input[i++]; } temp2[arg_count][k++] = '\0'; arg_count++; if(done == 1) { break; } } for(int i=0 ; i<arg_count ; i++) { cmdptr2[i] = temp2[i]; } arg_cnt[tok] = arg_count; } int main() { cout<<endl<<endl<<"Welcome to unique shell !!!!!!!!!!!"<<endl; tok=-1; while(1) { cout<<endl<<"***********UNIQUE**********"<<endl; cin.getline(input,81); count = 0,pip=0; splitcommand1(); if(pip == 1) { count++; splitcommand2(); } cout<<endl<<endl; if(strcmp(cmdptr1[0], "exit") == 0 ) { cout<<endl<<"EXITING UNIQUE SHELL"<<endl; exit(0); } //cout<<endl<<"Arg count is :"<<arg_count<<endl; if(pip == 1) { cout<<endl<<endl<<"in main :"; for(int i=0 ; i<arg_cnt[0] ; i++) { cout<<cmdptr1[i]<<" "; } cout<<endl; for(int i=0 ; i<arg_cnt[1] ; i++) { cout<<cmdptr2[i]<<" "; } pipe(cmdptr1, cmdptr2); } else { process (cmdptr1);//,arg_count); } } } I know it is not well coded. But try to help me :(

    Read the article

  • Issues with signal handling [closed]

    - by user34790
    I am trying to actually study the signal handling behavior in multiprocess system. I have a system where there are three signal generating processes generating signals of type SIGUSR1 and SIGUSR1. I have two handler processes that handle a particular type of signal. I have another monitoring process that also receives the signals and then does its work. I have a certain issue. Whenever my signal handling processes generate a signal of a particular type, it is sent to the process group so it is received by the signal handling processes as well as the monitoring processes. Whenever the signal handlers of monitoring and signal handling processes are called, I have printed to indicate the signal handling. I was expecting a uniform series of calls for the signal handlers of the monitoring and handling processes. However, looking at the output I could see like at the beginning the monitoring and signal handling processes's signal handlers are called uniformly. However, after I could see like signal handler processes handlers being called in a burst followed by the signal handler of monitoring process being called in a burst. Here is my code and output #include <iostream> #include <sys/types.h> #include <sys/wait.h> #include <sys/time.h> #include <signal.h> #include <cstdio> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> #define NUM_SENDER_PROCESSES 3 #define NUM_HANDLER_PROCESSES 4 #define NUM_SIGNAL_REPORT 10 #define MAX_SIGNAL_COUNT 100000 using namespace std; volatile int *usrsig1_handler_count; volatile int *usrsig2_handler_count; volatile int *usrsig1_sender_count; volatile int *usrsig2_sender_count; volatile int *lock_1; volatile int *lock_2; volatile int *lock_3; volatile int *lock_4; volatile int *lock_5; volatile int *lock_6; //Used only by the monitoring process volatile int monitor_count; volatile int usrsig1_monitor_count; volatile int usrsig2_monitor_count; double time_1[NUM_SIGNAL_REPORT]; double time_2[NUM_SIGNAL_REPORT]; //Used only by the main process int total_signal_count; //For shared memory int shmid; const int shareSize = sizeof(int) * (10); double timestamp() { struct timeval tp; gettimeofday(&tp, NULL); return (double)tp.tv_sec + tp.tv_usec / 1000000.; } pid_t senders[NUM_SENDER_PROCESSES]; pid_t handlers[NUM_HANDLER_PROCESSES]; pid_t reporter; void signal_catcher_1(int); void signal_catcher_2(int); void signal_catcher_int(int); void signal_catcher_monitor(int); void signal_catcher_main(int); void terminate_processes() { //Kill the child processes int status; cout << "Time up terminating the child processes" << endl; for(int i=0; i<NUM_SENDER_PROCESSES; i++) { kill(senders[i],SIGKILL); } for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { kill(handlers[i],SIGKILL); } kill(reporter,SIGKILL); //Wait for the child processes to finish for(int i=0; i<NUM_SENDER_PROCESSES; i++) { waitpid(senders[i], &status, 0); } for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { waitpid(handlers[i], &status, 0); } waitpid(reporter, &status, 0); } int main(int argc, char *argv[]) { if(argc != 2) { cout << "Required parameters missing. " << endl; cout << "Option 1 = 1 which means run for 30 seconds" << endl; cout << "Option 2 = 2 which means run until 100000 signals" << endl; exit(0); } int option = atoi(argv[1]); pid_t pid; if(option == 2) { if(signal(SIGUSR1, signal_catcher_main) == SIG_ERR) { perror("1"); exit(1); } if(signal(SIGUSR2, signal_catcher_main) == SIG_ERR) { perror("2"); exit(1); } } else { if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) { perror("1"); exit(1); } if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) { perror("2"); exit(1); } } if(signal(SIGINT, signal_catcher_int) == SIG_ERR) { perror("3"); exit(1); } /////////////////////////////////////////////////////////////////////////////////////// ////////////////////// Initializing the shared memory ///////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////// cout << "Initializing the shared memory" << endl; if ((shmid=shmget(IPC_PRIVATE,shareSize,IPC_CREAT|0660))< 0) { perror("shmget fail"); exit(1); } usrsig1_handler_count = (int *) shmat(shmid, NULL, 0); usrsig2_handler_count = usrsig1_handler_count + 1; usrsig1_sender_count = usrsig2_handler_count + 1; usrsig2_sender_count = usrsig1_sender_count + 1; lock_1 = usrsig2_sender_count + 1; lock_2 = lock_1 + 1; lock_3 = lock_2 + 1; lock_4 = lock_3 + 1; lock_5 = lock_4 + 1; lock_6 = lock_5 + 1; //Initialize them to be zero *usrsig1_handler_count = 0; *usrsig2_handler_count = 0; *usrsig1_sender_count = 0; *usrsig2_sender_count = 0; *lock_1 = 0; *lock_2 = 0; *lock_3 = 0; *lock_4 = 0; *lock_5 = 0; *lock_6 = 0; cout << "End of initializing the shared memory" << endl; ///////////////////////////////////////////////////////////////////////////////////////////// /////////////////// End of initializing the shared memory /////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////Registering the signal handlers/////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// cout << "Registering the signal handlers" << endl; for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { if((pid = fork()) == 0) { if(i%2 == 0) { struct sigaction action; action.sa_handler = signal_catcher_1; sigset_t block_mask; action.sa_flags = 0; sigaction(SIGUSR1,&action,NULL); if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) { perror("2"); exit(1); } } else { if(signal(SIGUSR1 ,SIG_IGN) == SIG_ERR) { perror("1"); exit(1); } struct sigaction action; action.sa_handler = signal_catcher_2; action.sa_flags = 0; sigaction(SIGUSR2,&action,NULL); } if(signal(SIGINT, SIG_DFL) == SIG_ERR) { perror("2"); exit(1); } while(true) { pause(); } exit(0); } else { //cout << "Registerd the handler " << pid << endl; handlers[i] = pid; } } cout << "End of registering the signal handlers" << endl; ///////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////End of registering the signal handlers ////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////Registering the monitoring process ////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////// cout << "Registering the monitoring process" << endl; if((pid = fork()) == 0) { struct sigaction action; action.sa_handler = signal_catcher_monitor; sigemptyset(&action.sa_mask); sigset_t block_mask; sigemptyset(&block_mask); sigaddset(&block_mask,SIGUSR1); sigaddset(&block_mask,SIGUSR2); action.sa_flags = 0; action.sa_mask = block_mask; sigaction(SIGUSR1,&action,NULL); sigaction(SIGUSR2,&action,NULL); if(signal(SIGINT, SIG_DFL) == SIG_ERR) { perror("2"); exit(1); } while(true) { pause(); } exit(0); } else { cout << "Monitor's pid is " << pid << endl; reporter = pid; } cout << "End of registering the monitoring process" << endl; ///////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////End of registering the monitoring process//////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //Sleep to make sure that the monitor and handler processes are well initialized and ready to handle signals sleep(5); ////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////Registering the signal generators/////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// cout << "Registering the signal generators" << endl; for(int i=0; i<NUM_SENDER_PROCESSES; i++) { if((pid = fork()) == 0) { if(signal(SIGUSR1, SIG_IGN) == SIG_ERR) { perror("1"); exit(1); } if(signal(SIGUSR2, SIG_IGN) == SIG_ERR) { perror("2"); exit(1); } if(signal(SIGINT, SIG_DFL) == SIG_ERR) { perror("2"); exit(1); } srand(i); while(true) { int signal_id = rand()%2 + 1; if(signal_id == 1) { killpg(getpgid(getpid()), SIGUSR1); while(__sync_lock_test_and_set(lock_4,1) != 0) { } (*usrsig1_sender_count)++; *lock_4 = 0; } else { killpg(getpgid(getpid()), SIGUSR2); while(__sync_lock_test_and_set(lock_5,1) != 0) { } (*usrsig2_sender_count)++; *lock_5=0; } int r = rand()%10 + 1; double s = (double)r/100; sleep(s); } exit(0); } else { //cout << "Registered the sender " << pid << endl; senders[i] = pid; } } //cout << "End of registering the signal generators" << endl; ///////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////End of registering the signal generators/////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// //Either sleep for 30 seconds and terminate the program or if the number of signals generated reaches 10000, terminate the program if(option = 1) { sleep(90); terminate_processes(); } else { while(true) { if(total_signal_count >= MAX_SIGNAL_COUNT) { terminate_processes(); } else { sleep(0.001); } } } } void signal_catcher_1(int the_sig) { while(__sync_lock_test_and_set(lock_1,1) != 0) { } (*usrsig1_handler_count) = (*usrsig1_handler_count) + 1; cout << "Signal Handler 1 " << *usrsig1_handler_count << endl; __sync_lock_release(lock_1); } void signal_catcher_2(int the_sig) { while(__sync_lock_test_and_set(lock_2,1) != 0) { } (*usrsig2_handler_count) = (*usrsig2_handler_count) + 1; __sync_lock_release(lock_2); } void signal_catcher_main(int the_sig) { while(__sync_lock_test_and_set(lock_6,1) != 0) { } total_signal_count++; *lock_6 = 0; } void signal_catcher_int(int the_sig) { for(int i=0; i<NUM_SENDER_PROCESSES; i++) { kill(senders[i],SIGKILL); } for(int i=0; i<NUM_HANDLER_PROCESSES; i++) { kill(handlers[i],SIGKILL); } kill(reporter,SIGKILL); exit(3); } void signal_catcher_monitor(int the_sig) { cout << "Monitoring process " << *usrsig1_handler_count << endl; } Here is the initial segment of output Monitoring process 0 Monitoring process 0 Monitoring process 0 Monitoring process 0 Signal Handler 1 1 Monitoring process 2 Signal Handler 1 2 Signal Handler 1 3 Signal Handler 1 4 Monitoring process 4 Monitoring process Signal Handler 1 6 Signal Handler 1 7 Monitoring process 7 Monitoring process 8 Monitoring process 8 Signal Handler 1 9 Monitoring process 9 Monitoring process 9 Monitoring process 10 Signal Handler 1 11 Monitoring process 11 Monitoring process 12 Signal Handler 1 13 Signal Handler 1 14 Signal Handler 1 15 Signal Handler 1 16 Signal Handler 1 17 Signal Handler 1 18 Monitoring process 19 Signal Handler 1 20 Monitoring process 20 Signal Handler 1 21 Monitoring process 21 Monitoring process 21 Monitoring process 22 Monitoring process 22 Monitoring process 23 Signal Handler 1 24 Signal Handler 1 25 Monitoring process 25 Signal Handler 1 27 Signal Handler 1 28 Signal Handler 1 29 Here is the segment when the signal handler processes signal handlers are called in a burst Signal Handler 1 456 Signal Handler 1 457 Signal Handler 1 458 Signal Handler 1 459 Signal Handler 1 460 Signal Handler 1 461 Signal Handler 1 462 Signal Handler 1 463 Signal Handler 1 464 Signal Handler 1 465 Signal Handler 1 466 Signal Handler 1 467 Signal Handler 1 468 Signal Handler 1 469 Signal Handler 1 470 Signal Handler 1 471 Signal Handler 1 472 Signal Handler 1 473 Signal Handler 1 474 Signal Handler 1 475 Signal Handler 1 476 Signal Handler 1 477 Signal Handler 1 478 Signal Handler 1 479 Signal Handler 1 480 Signal Handler 1 481 Signal Handler 1 482 Signal Handler 1 483 Signal Handler 1 484 Signal Handler 1 485 Signal Handler 1 486 Signal Handler 1 487 Signal Handler 1 488 Signal Handler 1 489 Signal Handler 1 490 Signal Handler 1 491 Signal Handler 1 492 Signal Handler 1 493 Signal Handler 1 494 Signal Handler 1 495 Signal Handler 1 496 Signal Handler 1 497 Signal Handler 1 498 Signal Handler 1 499 Signal Handler 1 500 Signal Handler 1 501 Signal Handler 1 502 Signal Handler 1 503 Signal Handler 1 504 Signal Handler 1 505 Signal Handler 1 506 Here is the segment when the monitoring processes signal handlers are called in a burst Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Monitoring process 140 Why isn't it uniform afterwards. Why are they called in a burst?

    Read the article

  • Optimizing sorting container of objects with heap-allocated buffers - how to avoid hard-copying buff

    - by Kache4
    I was making sure I knew how to do the op= and copy constructor correctly in order to sort() properly, so I wrote up a test case. After getting it to work, I realized that the op= was hard-copying all the data_. I figure if I wanted to sort a container with this structure (its elements have heap allocated char buffer arrays), it'd be faster to just swap the pointers around. Is there a way to do that? Would I have to write my own sort/swap function? #include <deque> //#include <string> //#include <utility> //#include <cstdlib> #include <cstring> #include <iostream> //#include <algorithm> // I use sort(), so why does this still compile when commented out? #include <boost/filesystem.hpp> #include <boost/foreach.hpp> using namespace std; namespace fs = boost::filesystem; class Page { public: // constructor Page(const char* path, const char* data, int size) : path_(fs::path(path)), size_(size), data_(new char[size]) { // cout << "Creating Page..." << endl; strncpy(data_, data, size); // cout << "done creating Page..." << endl; } // copy constructor Page(const Page& other) : path_(fs::path(other.path())), size_(other.size()), data_(new char[other.size()]) { // cout << "Copying Page..." << endl; strncpy(data_, other.data(), size_); // cout << "done copying Page..." << endl; } // destructor ~Page() { delete[] data_; } // accessors const fs::path& path() const { return path_; } const char* data() const { return data_; } int size() const { return size_; } // operators Page& operator = (const Page& other) { if (this == &other) return *this; char* newImage = new char[other.size()]; strncpy(newImage, other.data(), other.size()); delete[] data_; data_ = newImage; path_ = fs::path(other.path()); size_ = other.size(); return *this; } bool operator < (const Page& other) const { return path_ < other.path(); } private: fs::path path_; int size_; char* data_; }; class Book { public: Book(const char* path) : path_(fs::path(path)) { cout << "Creating Book..." << endl; cout << "pushing back #1" << endl; pages_.push_back(Page("image1.jpg", "firstImageData", 14)); cout << "pushing back #3" << endl; pages_.push_back(Page("image3.jpg", "thirdImageData", 14)); cout << "pushing back #2" << endl; pages_.push_back(Page("image2.jpg", "secondImageData", 15)); cout << "testing operator <" << endl; cout << pages_[0].path().string() << (pages_[0] < pages_[1]? " < " : " > ") << pages_[1].path().string() << endl; cout << pages_[1].path().string() << (pages_[1] < pages_[2]? " < " : " > ") << pages_[2].path().string() << endl; cout << pages_[0].path().string() << (pages_[0] < pages_[2]? " < " : " > ") << pages_[2].path().string() << endl; cout << "sorting" << endl; BOOST_FOREACH (Page p, pages_) cout << p.path().string() << endl; sort(pages_.begin(), pages_.end()); cout << "done sorting\n"; BOOST_FOREACH (Page p, pages_) cout << p.path().string() << endl; cout << "checking datas" << endl; BOOST_FOREACH (Page p, pages_) { char data[p.size() + 1]; strncpy((char*)&data, p.data(), p.size()); data[p.size()] = '\0'; cout << p.path().string() << " " << data << endl; } cout << "done Creating Book" << endl; } private: deque<Page> pages_; fs::path path_; }; int main() { Book* book = new Book("/some/path/"); }

    Read the article

  • how to use WaitForSingleobject

    - by Tyzak
    hello in order to try out how to programm with the win32 api i wrote a programm that creates a process. then i want to check if my proccess waits for the new created process, close the handle and then check waitforsingle obj. again. (the seconde process is sleeping for 700 ms) first process: #include <iostream> #include <windows.h> #include <string> using namespace std; void main() { bool ret; bool retwait; STARTUPINFO startupinfo; GetStartupInfo (&startupinfo); PROCESS_INFORMATION pro2info; wchar_t wcsCommandLine[] = L"D:\\betriebssystemePRA1PRO2.exe"; ret = CreateProcess(NULL, wcsCommandLine, NULL, NULL, false, CREATE_NEW_CONSOLE, NULL, NULL, &startupinfo, &pro2info); cout<<"hProcess: "<<pro2info.hProcess<<endl; cout<<"dwProcessId: "<<pro2info.dwProcessId <<endl; if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true) cout<<"waitprocess:true"<<endl; //prozess ist fertig else cout<<"waitprocess:false"<<endl; CloseHandle (pro2info.hProcess);//prozesshandle schließen, "verliert connection" if (retwait= WaitForSingleObject (pro2info.hProcess, INFINITE)==true)//wenn der prozess fertig ist cout<<"waitprocess:true"<<endl; else cout<<"waitprocess:false"<<endl; //cout<<GetLastError()<<endl; //gibt den letzten fehler aus ExitProcess(0); } seconde process: #include <iostream> #include <windows.h> #include <string> using namespace std; void main() { int b; b=GetCurrentProcessId(); cout<<b<<endl; cout<<"Druecken Sie Enter zum Beenden"<<endl; cin.get(); //warten bis Benutzer bestätigt Sleep (700); ExitProcess(0); cout<<"test"; } the first process prints false, false ; but it should print true, false. instead of the if-else statement is used this: //switch(WaitForSingleObject (pro2info.hProcess, INFINITE)){ // case WAIT_OBJECT_0: cout << "ja"; // break; // case WAIT_FAILED:cout << "nein"; // break; // case WAIT_TIMEOUT: // break; //} // cout<<"waitprocess:true"<<endl;//prozess ist fertig //else // cout<<"waitprocess:false"<<endl; and this seems to work. what did i wrong with my if-else statement? thanks in advance

    Read the article

  • Reading input from a text file, omits the first and adds a nonsense value to the end?

    - by Greenhouse Gases
    Hi there When I input locations from a txt file I am getting a peculiar error where it seems to miss off the first entry, yet add a garbage entry to the end of the link list (it is designed to take the name, latitude and longitude for each location you will notice). I imagine this to be an issue with where it starts collecting the inputs and where it stops but I cant find the error!! It reads the first line correctly but then skips to the next before adding it because during testing for the bug it had no record of the first location Lisbon though whilst stepping into the method call it was reading it. Very bizarre but hopefully someone knows the issue. Here is firstly my header file: #include <string> struct locationNode { char nodeCityName [35]; double nodeLati; double nodeLongi; locationNode* Next; void CorrectCase() // Correct upper and lower case letters of input { int MAX_SIZE = 35; int firstLetVal = this->nodeCityName[0], letVal; int n = 1; // variable for name index from second letter onwards if((this->nodeCityName[0] >90) && (this->nodeCityName[0] < 123)) // First letter is lower case { firstLetVal = firstLetVal - 32; // Capitalise first letter this->nodeCityName[0] = firstLetVal; } while(n <= MAX_SIZE - 1) { if((this->nodeCityName[n] >= 65) && (this->nodeCityName[n] <= 90)) { letVal = this->nodeCityName[n] + 32; this->nodeCityName[n] = letVal; } n++; } //cityNameInput = this->nodeCityName; } }; class Locations { private: int size; public: Locations(){ }; // constructor for the class locationNode* Head; //int Add(locationNode* Item); }; And here is the file containing main: // U08221.cpp : main project file. #include "stdafx.h" #include "Locations.h" #include <iostream> #include <string> #include <fstream> using namespace std; int n = 0,x, locationCount = 0, MAX_SIZE = 35; string cityNameInput; char targetCity[35]; bool acceptedInput = false, userInputReq = true, match = false, nodeExists = false;// note: addLocation(), set to true to enable user input as opposed to txt file locationNode *start_ptr = NULL; // pointer to first entry in the list locationNode *temp, *temp2; // Part is a pointer to a new locationNode we can assign changing value followed by a call to Add locationNode *seek, *bridge; void setElementsNull(char cityParam[]) { int y=0, count =0; while(cityParam[y] != NULL) { y++; } while(y < MAX_SIZE) { cityParam[y] = NULL; y++; } } void addLocation() { temp = new locationNode; // declare the space for a pointer item and assign a temporary pointer to it if(!userInputReq) // bool that determines whether user input is required in adding the node to the list { cout << endl << "Enter the name of the location: "; cin >> temp->nodeCityName; temp->CorrectCase(); setElementsNull(temp->nodeCityName); cout << endl << "Please enter the latitude value for this location: "; cin >> temp->nodeLati; cout << endl << "Please enter the longitude value for this location: "; cin >> temp->nodeLongi; cout << endl; } temp->Next = NULL; //set to NULL as when one is added it is currently the last in the list and so can not point to the next if(start_ptr == NULL){ // if list is currently empty, start_ptr will point to this node start_ptr = temp; } else { temp2 = start_ptr; // We know this is not NULL - list not empty! while (temp2->Next != NULL) { temp2 = temp2->Next; // Move to next link in chain until reach end of list } temp2->Next = temp; } ++locationCount; // increment counter for number of records in list if(!userInputReq){ cout << "Location sucessfully added to the database! There are " << locationCount << " location(s) stored" << endl; } } void populateList(){ ifstream inputFile; inputFile.open ("locations.txt", ios::in); userInputReq = true; temp = new locationNode; // declare the space for a pointer item and assign a temporary pointer to it do { inputFile.get(temp->nodeCityName, 35, ' '); setElementsNull(temp->nodeCityName); inputFile >> temp->nodeLati; inputFile >> temp->nodeLongi; setElementsNull(temp->nodeCityName); if(temp->nodeCityName[0] == 10) //remove linefeed from input { for(int i = 0; temp->nodeCityName[i] != NULL; i++) { temp->nodeCityName[i] = temp->nodeCityName[i + 1]; } } addLocation(); } while(!inputFile.eof()); userInputReq = false; cout << "Successful!" << endl << "List contains: " << locationCount << " entries" << endl; cout << endl; inputFile.close(); } bool nodeExistTest(char targetCity[]) // see if entry is present in the database { match = false; seek = start_ptr; int letters = 0, letters2 = 0, x = 0, y = 0; while(targetCity[y] != NULL) { letters2++; y++; } while(x <= locationCount) // locationCount is number of entries currently in list { y=0, letters = 0; while(seek->nodeCityName[y] != NULL) // count letters in the current name { letters++; y++; } if(letters == letters2) // same amount of letters in the name { y = 0; while(y <= letters) // compare each letter against one another { if(targetCity[y] == seek->nodeCityName[y]) { match = true; y++; } else { match = false; y = letters + 1; // no match, terminate comparison } } } if(match) { x = locationCount + 1; //found match so terminate loop } else{ if(seek->Next != NULL) { bridge = seek; seek = seek->Next; x++; } else { x = locationCount + 1; // end of list so terminate loop } } } return match; } void deleteRecord() // complete this { int junction = 0; locationNode *place; cout << "Enter the name of the city you wish to remove" << endl; cin >> targetCity; setElementsNull(targetCity); if(nodeExistTest(targetCity)) //if this node does exist { if(seek == start_ptr) // if it is the first in the list { junction = 1; } if(seek != start_ptr && seek->Next == NULL) // if it is last in the list { junction = 2; } switch(junction) // will alter list accordingly dependant on where the searched for link is { case 1: start_ptr = start_ptr->Next; delete seek; --locationCount; break; case 2: place = seek; seek = bridge; delete place; --locationCount; break; default: bridge->Next = seek->Next; delete seek; --locationCount; break; } } else { cout << targetCity << "That entry does not currently exist" << endl << endl << endl; } } void searchDatabase() { char choice; cout << "Enter search term..." << endl; cin >> targetCity; if(nodeExistTest(targetCity)) { cout << "Entry: " << endl << endl; } else { cout << "Sorry, that city is not currently present in the list." << endl << "Would you like to add this city now Y/N?" << endl; cin >> choice; /*while(choice != ('Y' || 'N')) { cout << "Please enter a valid choice..." << endl; cin >> choice; }*/ switch(choice) { case 'Y': addLocation(); break; case 'N': break; default : cout << "Invalid choice" << endl; break; } } } void printDatabase() { temp = start_ptr; // set temp to the start of the list do { if (temp == NULL) { cout << "You have reached the end of the database" << endl; } else { // Display details for what temp points to at that stage cout << "Location : " << temp->nodeCityName << endl; cout << "Latitude : " << temp->nodeLati << endl; cout << "Longitude : " << temp->nodeLongi << endl; cout << endl; // Move on to next locationNode if one exists temp = temp->Next; } } while (temp != NULL); } void nameValidation(string name) { n = 0; // start from first letter x = name.size(); while(!acceptedInput) { if((name[n] >= 65) && (name[n] <= 122)) // is in the range of letters { while(n <= x - 1) { while((name[n] >=91) && (name[n] <=97)) // ERROR!! { cout << "Please enter a valid city name" << endl; cin >> name; } n++; } } else { cout << "Please enter a valid city name" << endl; cin >> name; } if(n <= x - 1) { acceptedInput = true; } } cityNameInput = name; } int main(array<System::String ^> ^args) { //main contains test calls to functions at present cout << "Populating list..."; populateList(); printDatabase(); deleteRecord(); printDatabase(); cin >> cityNameInput; } The text file contains this (ignore the names, they are just for testing!!): Lisbon 45 47 Fattah 45 47 Darius 42 49 Peter 45 27 Sarah 85 97 Michelle 45 47 John 25 67 Colin 35 87 Shiron 40 57 George 34 45 Sean 22 33 The output omits Lisbon, but adds on a garbage entry with nonsense values. Any ideas why? Thank you in advance.

    Read the article

  • lnk2019 error in very simple c++ program

    - by Erin
    I have tried removing various parts and building, but nothing makes the lnk2019 error go away, or even produces any normal errors. Everything is in the one file at the moment (it won't be later when it is finished). The program has three lists of words and makes a jargon phrase out of them, and you are supposed to be able to add words, remove words, view the lists, restore defaults, save changes to file, and load changes from file. #include "stdafx.h" #include <iostream> #include <string.h> using namespace std; const int maxlist = 20; string adj1[maxlist], adj2[maxlist], noun[maxlist]; void defaultlist(int list) { if(list == 1) { adj1[0] = "green"; adj1[1] = "red"; adj1[2] = "yellow"; adj1[3] = "blue"; adj1[4] = "purple"; int i = 5; while(i != maxlist) { adj1[i] = ""; i = i + 1; } } if(list == 2) { adj2[0] = "shiny"; adj2[1] = "hard"; adj2[2] = "soft"; adj2[3] = "spiky"; adj2[4] = "furry"; int i = 5; while(i != maxlist) { adj2[i] = ""; i = i + 1; } } if(list == 3) { noun[0] = "cat"; noun[1] = "dog"; noun[2] = "desk"; noun[3] = "chair"; noun[4] = "door"; int i = 5; while(i != maxlist) { noun[i] = ""; i = i + 1; } } return; } void printlist(int list) { if(list == 1) { int i = 0; while(!(i == maxlist)) { cout << adj1[i] << endl; i = i + 1; } } if(list == 2) { int i = 0; while(!(i == maxlist)) { cout << adj2[i] << endl; i = i + 1; } } if(list == 3) { int i = 0; while(!(i == maxlist)) { cout << noun[i] << endl; i = i + 1; } } return; } string makephrase() { int num1 = rand()%maxlist; int num2 = rand()%maxlist; int num3 = rand()%maxlist; int num4 = rand()%1; string word1, word2, word3; if(num4 = 0) { word1 = adj1[num1]; word2 = adj2[num2]; } else { word1 = adj2[num1]; word2 = adj1[num2]; } word3 = noun[num3]; return word1 + " ," + word2 + " " + word3; } string addword(string word, int list) { string result; if(list == 1) { int i = 0; while(!(adj1[i] == "" || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "List is full. Please try again."; if(adj1[i] == "") { adj1[i] = word; result = "Word was entered successfully."; } } if(list == 2) { int i = 0; while(!(adj2[i] == "" || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "List is full. Please try again."; if(adj2[i] == "") { adj2[i] = word; result = "Word was entered successfully."; } } if(list == 3) { int i = 0; while(!(noun[i] == "" || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "List is full. Please try again."; if(noun[i] == "") { noun[i] = word; result = "Word was entered successfully."; } } return result; } string removeword(string word, int list) { string result; if(list == 1) { int i = 0; while(!(adj1[i] == word || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "Word is not on the list. Please try again."; if(adj1[i] == word) { adj1[i] = ""; result = "Word was removed successfully."; } } if(list == 2) { int i = 0; while(!(adj2[i] == word || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "Word is not on the list. Please try again."; if(adj2[i] == word) { adj2[i] = ""; result = "Word was removed successfully."; } } if(list == 3) { int i = 0; while(!(noun[i] == word || i == maxlist)) { i = i + 1; } if(i == maxlist) result = "Word is not on the list. Please try again."; if(noun[i] == word) { noun[i] = ""; result = "Word was removed successfully."; } } return result; } /////////////////////////////main/////////////////////////////////// int main() { string mainselection; string makeselection; string phrase; defaultlist(1); defaultlist(2); defaultlist(3); cout << "This program generates jargon phrases made of two adjectives and one noun,"; cout << " on three lists. Each list may contain a maximum of " << maxlist << "elements."; cout << " Please choose from the following menu by typing the appropriate number "; cout << "and pressing enter." << endl; cout << endl; cout << "1. Make a jargon phrase." << endl; cout << "2. View a list." << endl; cout << "3. Add a word to a list." << endl; cout << "4. Remove a word from a list." << endl; cout << "5. Restore default lists." << endl; cout << "More options coming soon!." << endl; cin mainselection if(mainselection == 1) { phrase = makephrase(); cout << "Your phrase is " << phrase << "." << endl; cout << "To make another phrase, press 1. To go back to the main menu,"; cout << " press 2. To exit the program, press 3." << endl; cin makeselection; while(!(makeselection == "1" || makeselection == "2" || makeselection == "3")) { cout << "You have entered an invalid selection. Please try again." << endl; cin makeselection; } while(makeselection == "1") { phrase = makephrase(); cout << "To make another phrase, press 1. To go back to the main menu,"; cout << " press 2. To exit the program, press 3." << endl; } if(makeselection == "2") main(); if(makeselection == "3") return 0; } return 0; } //Rest of the options coming soon!

    Read the article

  • How can I fix my program from crashing in C++?

    - by Rachel
    I'm very new to programming and I am trying to write a program that adds and subtracts polynomials. My program sometimes works, but most of the time, it randomly crashes and I have no idea why. It's very buggy and has other problems I'm trying to fix, but I am unable to really get any further coding done since it crashes. I'm completely new here but any help would be greatly appreciated. Here's the code: #include <iostream> #include <cstdlib> using namespace std; int getChoice(void); class Polynomial10 { private: double* coef; int degreePoly; public: Polynomial10(int max); //Constructor for a new Polynomial10 int getDegree(){return degreePoly;}; void print(); //Print the polynomial in standard form void read(); //Read a polynomial from the user void add(const Polynomial10& pol); //Add a polynomial void multc(double factor); //Multiply the poly by scalar void subtract(const Polynomial10& pol); //Subtract polynom }; void Polynomial10::read() { cout << "Enter degree of a polynom between 1 and 10 : "; cin >> degreePoly; cout << "Enter space separated coefficients starting from highest degree" << endl; for (int i = 0; i <= degreePoly; i++) { cin >> coef[i]; } } void Polynomial10::print() { for(int i=0;i<=degreePoly;i++) { if(coef[i] == 0) { cout << ""; } else if(i>=0) { if(coef[i] > 0 && i!=0) { cout<<"+"; } if((coef[i] != 1 && coef[i] != -1) || i == degreePoly) { cout << coef[i]; } if((coef[i] != 1 && coef[i] != -1) && i!=degreePoly ) { cout << "*"; } if (i != degreePoly && coef[i] == -1) { cout << "-"; } if(i != degreePoly) { cout << "x"; } if ((degreePoly - i) != 1 && i != degreePoly) { cout << "^"; cout << degreePoly-i; } } } } void Polynomial10::add(const Polynomial10& pol) { for(int i = 0; i<degreePoly; i++) { int degree = degreePoly; coef[degreePoly-i] += pol.coef[degreePoly-(i+1)]; } } void Polynomial10::subtract(const Polynomial10& pol) { for(int i = 0; i<degreePoly; i++) { coef[degreePoly-i] -= pol.coef[degreePoly-(i+1)]; } } void Polynomial10::multc(double factor) { //int degreePoly=0; //double coef[degreePoly]; cout << "Enter the scalar multiplier : "; cin >> factor; for(int i = 0; i<degreePoly; i++) { coef[i] *= factor; } }; Polynomial10::Polynomial10(int max) { degreePoly=max; coef = new double[degreePoly]; for(int i; i<degreePoly; i++) { coef[i] = 0; } } int main() { int choice; Polynomial10 p1(1),p2(1); cout << endl << "CGS 2421: The Polynomial10 Class" << endl << endl << endl; cout << "0. Quit\n" << "1. Enter polynomial\n" << "2. Print polynomial\n" << "3. Add another polynomial\n" << "4. Subtract another polynomial\n" << "5. Multiply by scalar\n\n"; int choiceFirst = getChoice(); if (choiceFirst != 1) { cout << "Enter a Polynomial first!"; } if (choiceFirst == 1) {choiceFirst = choice;} while(choice != 0) { switch(choice) { case 0: return 0; case 1: p1.read(); break; case 2: p1.print(); break; case 3: p2.read(); p1.add(p2); cout << "Updated Polynomial: "; p1.print(); break; case 4: p2.read(); p1.subtract(p2); cout << "Updated Polynomial: "; p1.print(); break; case 5: p1.multc(10); cout << "Updated Polynomial: "; p1.print(); break; } choice = getChoice(); } return 0; } int getChoice(void) { int c; cout << "\nEnter your choice : "; cin >> c; return c; }

    Read the article

  • Asks for Account Type twice

    - by André Fecteau
    Been working on this program for a while now. (had some problems and asked a few times here.) Ran into another one though! The program asks for my account type twice. Can not figure out why or how to fix it. Any help is appreciated, thanks! /* project3.cpp Andre Fecteau CSC135-101 October 29, 2013 This program prints a bank's service fees per month depending on account type */ #include <iostream> using namespace std; /* Basic Function for Copy Paste <function type> <function name> (){ // Declarations // Initalizations // Input // Process // Output // Prolouge } */ void displayInstructions (){ // Declarations // Initalizations // Input // Process // Output cout <<"| -------------------------------------------------------------- |" << endl; cout <<"| ---------- Welcome to the bank fee calculator ---------------- |" << endl; cout <<"| -------------------------------------------------------------- |" << endl; cout <<"| This Program wil ask you to eneter your account number. |" << endl; cout <<"| Then it will ask for your account type Personal or Commercial. |" << endl; cout <<"| Then ask for the amount of checks you have written. |" << endl; cout <<"| Lastly it will output how much your fees are for this month. |" << endl; cout <<"| -------------------------------------------------------------- |" << endl; cout << endl; // Prolouge } int readAccNumb(){ // delarations int accNumber; // intitalizations accNumber = 0.0; // input cout << "Please Enter Account Number:"; cin >> accNumber; // Procesas // output // prolouge return accNumber; } int checksWritten (){ // Declarations int written; // Initalizations written = 0.0; // Input cout <<"Please input the amount of checks you have written this month:"; cin >> written; // Output // Prolouge return written; } char accType (){ // Declarations char answer; int numberBySwitch; // Initalizations numberBySwitch = 1; // Input while (numberBySwitch == 1){ cout << "Please Enter the acount type (C for Comerical and P for Personal):"; cin >> answer; // Process switch (answer){ case 'p': answer = 'P'; numberBySwitch += 2;break; case 'P': numberBySwitch += 2;break; case 'c': answer = 'C'; numberBySwitch += 3;break; case 'C': numberBySwitch += 3;break; default: if(numberBySwitch == 1) { cout << "Error! Please enter a correct type!" <<endl; } } } // Output // Prolouge return answer; } int commericalCalc(int checksWritten){ // Declarations int written; int checkPrice; // Initalizations checkPrice = 0.0; // Input // Process if(written < 20){ checkPrice = 0.10; } // Output // Prolouge return checkPrice; } int personalCalc(int checksWritten){ } double pricePerCheck(char accType, int checksWritten){ // Declarations double price; char answer; // Initalizations price = 0.0; // Input // Process if(accType == 'P'){ } if(accType == 'C'){ if(checksWritten < 20){ price = 0.10; } } // Output // Prolouge return price; } int main(){ // Declarations int accountNumb; char theirAccType; int writtenChecks; double split; // Initalizations accountNumb = 0.0; writtenChecks = 0.0; split = 0.0; theirAccType = ' '; // Input displayInstructions(); theirAccType = accType(); accountNumb = readAccNumb(); split = pricePerCheck(accType(), checksWritten()); // Output cout << endl; cout << "Account Type: " << theirAccType << endl; cout << "Check Price: " << split << endl; // Prolouge return 0; }

    Read the article

  • What is wrong in this c++ code?

    - by narayanpatra
    Why this coder do not show error #include <iostream> int main() { using namespace std; unsigned short int myInt = 99; unsigned short int * pMark = 0; cout << myInt << endl; pMark = &myInt; *pMark = 11; cout << "*pMark:\t" << *pMark << "\nmyInt:\t" << myInt << endl; return 0; } But this one shows : #include<iostream> using namespace std; int addnumber(int *p, int *q){ cout << *p = 12 << endl; cout << *q = 14 << endl; } #include<iostream> using namespace std; int addnumber(int *p, int *q){ cout << *p = 12 << endl; cout << *q = 14 << endl; } int main() { int i , j; cout << "enter the value of first number"; cin >> i; cout << "enter the value of second number"; cin >> j; addnumber(&i, &j); cout << i << endl; cout << j << endl; } In both the code snippets, I am assigning *pointer=somevalue. In first code it do not show any error but it shows error in the line cout << *p = 12 << endl; cout << *q = 14 << endl; What mistake I am doing ?

    Read the article

  • How to use enumeration types in C++?

    - by Sagistic
    I do not understand how to use enumeration types. I understand what they are, but I don't quite get their purpose. I have made a program that inputs three sides of a triangle and outputs whether or not they are isosceles, scalene, or equilateral. I'm suppose to incorporate the enumeration type somewhere, but don't get where and how to use them. Any help would be appreciated. #include <iostream> using namespace std; enum triangleType {scalene, isosceles, equilateral, noTriangle}; void triangleShape(double x, double y, double z); int main() { double x, y, z; cout << "Please enter the three sides of a triangle:" << endl; cout << "Enter side 1: "; cin >> x; cout << endl; cout << "Enter side 2: "; cin >> y; cout << endl; cout << "Enter side 3: "; cin >> z; cout << endl; triangleShape(x, y, z); return 0; } void triangleShape(double x, double y, double z) { if (((x+y) > z) && ((x+z) > y) && ((y+z) > x)) { cout << "You have a triangle!" << endl; if (x == y && y == z) cout << "Your triangle is an equilateral" << endl; else if (x == y || x == z || y == z) cout << "Your triangle is an isosceles" << endl; else cout << "Your triangle is a scalene" << endl; } else if ((x+y) <= z || ((x+z) <= y) || ((y+z) <= x)) cout << "You do not have a triangle." << endl; }

    Read the article

  • How to use enumeration types in C++? Apply within example.

    - by Sagistic
    I do not understand how to use enumeration types. I understand what they are, but I don't quite get their purpose. I have made a program that inputs three sides of a triangle and outputs whether or not they are isosceles, scalene, or equilateral. I'm suppose to incorporate the enumeration type somewhere, but don't get where and how to use them. Any help would be appreciated. // h8p466x1.cpp : Defines the entry point for the console application. // include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } include using namespace std; enum triangleType {scalene, isosceles, equilateral, noTriangle}; void triangleShape(double x, double y, double z); int main() { double x, y, z; cout << "Please enter the three sides of a triangle:" << endl; cout << "Enter side 1: "; cin >> x; cout << endl; cout << "Enter side 2: "; cin >> y; cout << endl; cout << "Enter side 3: "; cin >> z; cout << endl; triangleShape(x, y, z); return 0; } void triangleShape(double x, double y, double z) { if (((x+y) z) && ((x+z) y) && ((y+z) x)) { cout << "You have a triangle!" << endl; if (x == y && y == z) cout << "Your triangle is an equilateral" << endl; else if (x == y || x == z || y == z) cout << "Your triangle is an isosceles" << endl; else cout << "Your triangle is a scalene" << endl; } else if ((x+y) <= z || ((x+z) <= y) || ((y+z) <= x)) cout << "You do not have a triangle." << endl; }

    Read the article

  • Does cout need to be terminated with a semicolon ?

    - by Philippe Harewood
    I am reading Bjarne Stroustrup's Programming : Principles and Practice Using C++ In the drill section for Chapter 2 it talks about various ways to look at typing errors when compiling the hello_world program #include "std_lib_facilities.h" int main() //C++ programs start by executing the function main { cout << "Hello, World!\n", // output "Hello, World!" keep_window_open(); // wait for a character to be entered return 0; } In particular this section asks: Think of at least five more errors you might have made typing in your program (e.g. forget keep_window_open(), leave the Caps Lock key on while typing a word, or type a comma instead of a semicolon) and try each to see what happens when you try to compile and run those versions. For the cout line, you can see that there is a comma instead of a semicolon. This compiles and runs (for me). Is it making an assumption ( like in the javascript question: Why use semicolon? ) that the statement has been terminated ? Because when I try for keep_terminal_open(); the compiler informs me of the semicolon exclusion.

    Read the article

  • How odd this function is? It works in a test project, however, it goes wrong in my project?(Windows Socket) [closed]

    - by user67449
    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){ memset(sockBuf, 0, sizeof(sockBuf)); bytesSend=send(sock, &sockBuf[idx], bytesLeft, 0); cout<<"??send()??, bytesSend: "<<bytesSend<<endl; if(bytesSend==SOCKET_ERROR){ cout<<"Error at send()."<<endl; cout<<"Error # "<<WSAGetLastError()<<" happened."<<endl; return 1; } bytesLeft-=bytesSend; idx+=bytesSend; } cout<<"DataPack ???????"<<endl; return 0; } This is the function I defined, which is used to send a user_defined structure DataPack. My code in test project is as follows: char sendBuf[100000]; int res=SockSend(dataPack, sockConn, sendBuf); if(res==1){ cout<<"SockSend()???"<<endl; }else{ cout<<"SockSend()???"<<endl; } My code in my current project is: err=SockSend(dataPackSend, sockConn, sockBuf); if(err==1){ cout<<"SockSend()??"<<endl; exit(0); }else{ cout<<"??? "<<dataPackSend.packNum<<" ?DataPack(??)"<<endl; } Can you tell me where does this function go wrong? I will be appreciated for you answer.

    Read the article

  • C++ cin keeps skipping.....

    - by user69514
    I am having problems with my program. WHen I run it, it asks the user for the album, the title, but then it just exits the loop without asking for the price and the sale tax. Any ideas what's going on? This is a sample run Discounts effective for September 15, 2010 Classical 8% Country 4% International 17% Jazz 0% Rock 16% Show 12% Are there more transactions? Y/N y Enter Artist of CD: Sevendust Enter Title of CD: Self titled Enter Genre of CD: Rock enter price Are there more transactions? Y/N Thank you for shopping with us! Program code: #include <iostream> #include <string> using namespace std; int counter = 0; string discount_tiles[] = {"Classical", "Country", "International", "Jazz", "Rock", "Show"}; int discount_amounts[] = {8, 4, 17, 0, 16, 12, 14}; string date = "September 15, 2010"; // Array Declerations //Artist array char** artist = new char *[100]; //Title array char** title = new char *[100]; //Genres array char** genres = new char *[100]; //Price array double* price[100]; //Discount array double* tax[100]; // sale price array double* sale_price[100]; //sale tax array double* sale_tax[100]; //cash price array double* cash_price[100]; //Begin Prototypes char* getArtist(); char* getTitle(); char* getGenre(); double* getPrice(); double* getTax(); unsigned int* AssignDiscounts(); void ReadTransaction (char ** artist, char ** title, char ** genre, float ** cash, float & taxrate, int albumcount); void computesaleprice(); bool AreThereMore (); //End Prototypes bool areThereMore () { char answer; cout << "Are there more transactions? Y/N" << endl; cin >> answer; if (answer =='y' || answer =='Y') return true; else return false; } char* getArtist() { char * artist= new char [100]; cout << "Enter Artist of CD: " << endl; cin.getline(artist,100); cin.ignore(); return artist; } char* getTitle() { char * title= new char [100]; cout << "Enter Title of CD: " << endl; cin.getline(title,100); cin.ignore(); return title; } char* getGenre() { char * genre= new char [100]; cout << "Enter Genre of CD: " << endl; cin.getline(genre,100); cin.ignore(); return genre; } double* getPrice() { //double* price = new double(); //cout << "Enter Price of CD: " << endl; //cin >> *price; //return price; double p = 0.0; cout<< "enter price" << endl; cin >> p; cin.ignore(); double* pp = &p; return pp; } double* getTax() { double* tax= new double(); cout << "Enter local sales tax: " << endl; cin >> *tax; return tax; } int findDiscount(string str){ if(str.compare(discount_tiles[0]) == 0) return discount_amounts[0]; else if(str.compare(discount_tiles[0]) == 0) return discount_amounts[1]; else if(str.compare(discount_tiles[0]) == 0) return discount_amounts[2]; else if(str.compare(discount_tiles[0]) == 0) return discount_amounts[3]; else if(str.compare(discount_tiles[0]) == 0) return discount_amounts[4]; else if(str.compare(discount_tiles[0]) == 0) return discount_amounts[5]; else{ cout << "Error in findDiscount function" << endl; return 0; } } void computesaleprice() { /** fill in array for all purchases **/ for( int i=0; i<=counter; i++){ double temp = *price[i]; temp -= findDiscount(genres[i]); double* tmpPntr = new double(); tmpPntr = &temp; sale_price[i] = tmpPntr; delete(&temp); delete(tmpPntr); } } void printDailyDiscounts(){ cout << "Discounts effective for " << date << endl; for(int i=0; i < 6; i++){ cout << discount_tiles[i] << "\t" << discount_amounts[i] << "%" << endl; } } //Begin Main int main () { for( int i=0; i<100; i++){ artist[i]=new char [100]; title[i]=new char [100]; genres[i]=new char [100]; price[i] = new double(0.0); tax[i] = new double(0.0); } // End Array Decleration printDailyDiscounts(); bool flag = true; while(flag == true){ if(areThereMore() == true){ artist[counter] = getArtist(); title[counter] = getTitle(); genres[counter] = getGenre(); price[counter] = getPrice(); //tax[counter] = getTax(); //counter++; flag = true; } else { flag = false; } } //compute sale prices //computesaleprice(); cout << "Thank you for shopping with us!" << endl; return 0; } //End Main /** void ReadTransaction (char ** artist, char ** title, char ** genre, float ** cash, float & taxrate, int albumcount) { strcpy(artist[albumcount],getArtist()); strcpy(title[albumcount],getTitle()); strcpy(genre[albumcount],getGenre()); //cash[albumcount][0]=computesaleprice();??????? //taxrate=getTax;?????????????? } * * */ unsigned int * AssignDiscounts() { unsigned int * discount = new unsigned int [7]; cout << "Enter Classical Discount: " << endl; cin >> discount[0]; cout << "Enter Country Discount: " << endl; cin >> discount[1]; cout << "Enter International Discount: " << endl; cin >> discount[2]; cout << "Enter Jazz Discount: " << endl; cin >> discount[3]; cout << "Enter Pop Discount: " << endl; cin >> discount[4]; cout << "Enter Rock Discount: " << endl; cin >> discount[5]; cout << "Enter Show Discount: " << endl; cin >> discount[6]; return discount; } /** char ** AssignGenres () { char ** genres = new char * [7]; for (int x=0;x<7;x++) genres[x] = new char [20]; strcpy(genres [0], "Classical"); strcpy(genres [1], "Country"); strcpy(genres [2], "International"); strcpy(genres [3], "Jazz"); strcpy(genres [4], "Pop"); strcpy(genres [5], "Rock"); strcpy(genres [6], "Show"); return genres; } **/ float getTax(float taxrate) { cout << "Please enter store tax rate: " << endl; cin >> taxrate; return taxrate; }

    Read the article

  • C++ Multithreading with pthread is blocking (including sockets)

    - by Sebastian Büttner
    I am trying to implement a multi threaded application with pthread. I did implement a thread class which looks like the following and I call it later twice (or even more), but it seems to block instead of execute the threads parallel. Here is what I got until now: The Thread Class is an abstract class which has the abstract method "exec" which should contain the thread code in a derive class (I did a sample of this, named DerivedThread) Thread.hpp #ifndef THREAD_H_ #define THREAD_H_ #include <pthread.h> class Thread { public: Thread(); void start(); void join(); virtual int exec() = 0; int exit_code(); private: static void* thread_router(void* arg); void exec_thread(); pthread_t pth_; int code_; }; #endif /* THREAD_H_ */ And Thread.cpp #include <iostream> #include "Thread.hpp" /*****************************/ using namespace std; Thread::Thread(): code_(0) { cout << "[Thread] Init" << endl; } void Thread::start() { cout << "[Thread] Created Thread" << endl; pthread_create( &pth_, NULL, Thread::thread_router, reinterpret_cast<void*>(this)); } void Thread::join() { cout << "[Thread] Join Thread" << endl; pthread_join(pth_, NULL); } int Thread::exit_code() { return code_; } void Thread::exec_thread() { cout << "[Thread] Execute" << endl; code_ = exec(); } void* Thread::thread_router(void* arg) { cout << "[Thread] exec_thread function in thread" << endl; reinterpret_cast<Thread*>(arg)->exec_thread(); return NULL; } DerivedThread.hpp #include "Thread.hpp" class DerivedThread : public Thread { public: DerivedThread(); virtual ~DerivedThread(); int exec(); void Close() = 0; DerivedThread.cpp [...] #include "DerivedThread.cpp" [...] int DerivedThread::exec() { //code to be executed do { cout << "Thread executed" << endl; usleep(1000000); } while (true); //dummy, just to let it run for a while } [...] Basically, I am calling this like the here: DerivedThread *thread; cout << "Creating Thread" << endl; thread = new DerivedThread(); cout << "Created thread, starting..." << endl; thread->start(); cout << "Started thread" << endl; cout << "Creating 2nd Thread" << endl; thread = new DerivedThread(); cout << "Created 2nd thread, starting..." << endl; thread->start(); cout << "Started 2nd thread" << endl; What is working great if I am only starting one of these Threads , but if I start multiple which should run together (not synced, only parallel) . But I discovered, that the thread is created, then as it tries to execute it (via start) the problem seems to block until the thread has closed. After that the next Thread is processed. I thought that pthread would do it unblocked for me, so what did I wrong? A sample output might be: Creating Thread [Thread] Thread Init Created thread, starting... [Thread] Created thread [Thread] exec_thread function in thread [Thread] Execute Thread executed Thread executed Thread executed Thread executed Thread executed Thread executed Thread executed .... Until Thread 1 is not terminated, a Thread 2 won't be created not executed. The process above is executed in an other class. Just for the information: I am trying to create a multi threaded server. The concept is like this: MultiThreadedServer Class has a main loop, like this one: ::inet::ServerSock *sock; //just a simple self made wrapper class for sockets DerivedThread *thread; for (;;) { sock = new ::inet::ServerSock(); this->Socket->accept( *sock ); cout << "Creating Thread" << endl; //Threads (according to code sample above) thread = new DerivedThread(sock); //I did not mentoine the parameter before as it was not neccesary, in fact, I pass the socket handle with the connected socket to the thread cout << "Created thread, starting..." << endl; thread->start(); cout << "Started thread" << endl; } So I thought that this would loop over and over and wait for new connections to accept. and when a new client arrives, I am creating a new thread and give the thread the connected socket as a parameter. In the DerivedThread::exec I am doing the handling for the connected client. Like: [...] do { [...] if (this-sock_-read( Buffer, sizeof(PacketStruc) ) 0) { cout << "[Handler_Base] Recv Packet" << endl; //handle the packet } else { Connected = false; } delete Buffer; } while ( Connected ); So I loop in the created thread as long as the client keeps the connection. I think, that the socket may cause the blocking behaviour. Edit: I figured out, that it is not the read() loop in the DerivedThread Class as I simply replaced it with a loop over a simple cout-usleep part. It did also only execute the first one and after first thread finished, the 2nd one was executed. Many thanks and best regards, Sebastian

    Read the article

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