Quantcast
Channel: CodeGuru Forums - Visual C++ Programming
Viewing all 3027 articles
Browse latest View live

How to set up CTRL_CLOSE_EVENT

$
0
0
Hi I'm relatively new to creating servers, using sockets etc. I am creating a multithreaded server which allows multiple users to connect, I want to implement a method where when the client exits it should send a quit message to the server, I have been trying to do this by using CTRL_CLOSE_EVENT but can not get my head round how to use it.

here is my client code that I am trying to implement the close event on
Code:

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>

// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")


#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
using namespace std;

static BOOL CtrlHandler(DWORD fdwCtrlType)
{
        switch (fdwCtrlType)
        {
                // Handle the CTRL-C signal.
        case CTRL_CLOSE_EVENT:
                Beep(600, 200);
                printf("Ctrl-Close event\n\n");
                return(TRUE);
        default:
                return FALSE;
        }
}
int __cdecl main(int argc, char **argv)
{
        WSADATA wsaData;
        DWORD fdwcontroltype = SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
       
        SOCKET ConnectSocket = INVALID_SOCKET;
        struct addrinfo *result = NULL,
                *ptr = NULL,
                hints;
        char *sendbuf = "this is a test";
        char recvbuf[DEFAULT_BUFLEN];
        int iResult;
        int recvbuflen = DEFAULT_BUFLEN;

       

        // Initialize Winsock
        iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
        if (iResult != 0) {
                printf("WSAStartup failed with error: %d\n", iResult);
                return 1;
        }

        ZeroMemory(&hints, sizeof(hints));
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;

        // Resolve the server address and port
        iResult = getaddrinfo("127.0.0.1", DEFAULT_PORT, &hints, &result);
        if (iResult != 0) {
                printf("getaddrinfo failed with error: %d\n", iResult);
                WSACleanup();
                return 1;
        }

        // Attempt to connect to an address until one succeeds
        for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {

                // Create a SOCKET for connecting to server
                ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
                        ptr->ai_protocol);
                if (ConnectSocket == INVALID_SOCKET) {
                        printf("socket failed with error: %ld\n", WSAGetLastError());
                        WSACleanup();
                        return 1;
                }

                // Connect to server.
                iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
                if (iResult == SOCKET_ERROR) {
                        closesocket(ConnectSocket);
                        ConnectSocket = INVALID_SOCKET;
                        continue;
                }
                break;
        }

        freeaddrinfo(result);

        if (ConnectSocket == INVALID_SOCKET) {
                printf("Unable to connect to server!\n");
                WSACleanup();
                return 1;
        }

        // Send an initial buffer
        iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
        if (iResult == SOCKET_ERROR) {
                printf("send failed with error: %d\n", WSAGetLastError());
                closesocket(ConnectSocket);
                WSACleanup();
                return 1;
        }

        printf("Bytes Sent: %ld\n", iResult);

       
        int quit = 1;
        // Send and Receive until the peer closes the connection
        do {
               
               
                iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
               
                        if (iResult > 0)
                                printf("Bytes received: %d\n", iResult);
                        else if (iResult == 0)
                                printf("Connection closed\n");
                        else
                                printf("recv failed with error: %d\n", WSAGetLastError());
                        if (fdwcontroltype == CTRL_CLOSE_EVENT)
                        {

                                send(ConnectSocket, (char*)&quit, sizeof(quit), 0);

                                iResult = shutdown(ConnectSocket, SD_BOTH);
                                if (iResult == SOCKET_ERROR) {
                                        printf("shutdown failed with error: %d\n", WSAGetLastError());
                                        closesocket(ConnectSocket);
                                        WSACleanup();
                                        return 1;
                                }
                }
        } while (iResult > 0);

        // shutdown the connection since no more data will be sent
        iResult = shutdown(ConnectSocket, SD_SEND);
        if (iResult == SOCKET_ERROR) {
                printf("shutdown failed with error: %d\n", WSAGetLastError());
                closesocket(ConnectSocket);
                WSACleanup();
                return 1;
        }
        // cleanup
        closesocket(ConnectSocket);
        WSACleanup();
        system("PAUSE");
        return 0;
}

here is my server code if you want to try and use it, you will need to remove game.h include
Code:

#undef UNICODE

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <mutex>
#include <iostream>
#include <string>
#include "game.h"
#include <fstream>

// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")
// #pragma comment (lib, "Mswsock.lib")
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
#define DEFAULT_IP "127.0.0.1 "
std::mutex MyMutex;
int ClientCount;
using namespace std;
std::ofstream outfile ("serverconfig.txt", std::ofstream::out | std::ofstream::app);
int callThread(SOCKET ClientSocket,int ClientCount )
{
       
        char recvbuf[DEFAULT_BUFLEN];
       
        int recvbuflen = DEFAULT_BUFLEN;
                int iResult, iSendResult;
                // Receive until the peer shuts down the connection
                       
                printf("thread count: %d\n", ClientCount);
                        do {
                       

                                iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
                                        if (iResult == 1)
                                        {
                                               
                                                cout << "Client " << ClientCount << " has left" << endl;
                                                closesocket(ClientSocket);
                                                ClientCount--;
                                               
                                        }
                                        if (iResult > 0) {
                                               
                                                        printf("Bytes received: %d\n", iResult);
                                               

                                                       
                                                        // Echo the buffer back to the sender
                                                       
                                                        iSendResult = send(ClientSocket, recvbuf, iResult, 0);
                                               
                                                        if (iSendResult == SOCKET_ERROR) {
                                                               
                                                                        printf("send failed: %d\n", WSAGetLastError());
                                                               
                                                                        closesocket(ClientSocket);
                                                                        ClientCount--;
                                                                        return 1;
                                                               
                                                        }
                                               
                                                        printf("Bytes sent: %d\n", iSendResult);
                                               
                                        }
                               
                                        else if (iResult == 0)
                                        {
                                                ClientCount--;
                                                printf("Connection closing...\n");
                                        }
                                        else {
                                       
                                                printf("recv failed: %d\n", WSAGetLastError());
                                       
                                                closesocket(ClientSocket);
                                                ClientCount--;
                                                return 1;
                                       
                                }
                                       
                        } while (iResult > 0);

                       
}


int __cdecl main(void)
{
        WSADATA wsaData;
        int iResult;

        SOCKET ListenSocket = INVALID_SOCKET;
        SOCKET ClientSocket = INVALID_SOCKET;

        struct addrinfo *result = NULL;
        struct addrinfo hints;

        int iSendResult;
        ClientCount = 0;
        char recvbuf[DEFAULT_BUFLEN];
        int recvbuflen = DEFAULT_BUFLEN;
        std::thread myThreads[100];
        game game1;
        string type;
        string map;
        int level;
        int max;
        int min;
        //output server details to file
        ofstream outfile;
        outfile.open("serverconfig.txt");
        outfile << DEFAULT_IP;
        outfile << DEFAULT_PORT;
        outfile.close();
        //get start up data
        /*cout << "please choose a type: 1: Deathmatch 2: Capture the flag 3: Blood Diamond" << endl;
        cin >> type;
        cout << "Please choose a map:" << endl;
        cin >> map;
        cout << "please choose a difficulty level between 1 - 3: " << endl;
        cin >> level;
        cout << "Please choose the max number of clients: " << endl;
        cin >> max;
        cout << "Please choose the min number of clients" << endl;
        cin >> min; */

        // Initialize Winsock
        iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
        if (iResult != 0) {
                printf("WSAStartup failed with error: %d\n", iResult);
                return 1;
        }

        ZeroMemory(&hints, sizeof(hints));
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_protocol = IPPROTO_TCP;
        hints.ai_flags = AI_PASSIVE;

        // Resolve the server address and port
        iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
        if (iResult != 0) {
                printf("getaddrinfo failed with error: %d\n", iResult);
                WSACleanup();
                return 1;
        }

        // Create a SOCKET for connecting to server
        ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
        if (ListenSocket == INVALID_SOCKET) {
                printf("socket failed with error: %ld\n", WSAGetLastError());
                freeaddrinfo(result);
                WSACleanup();
                return 1;
        }

        // Setup the TCP listening socket
        iResult = ::bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
        if (iResult == SOCKET_ERROR) {
                printf("bind failed with error: %d\n", WSAGetLastError());
                freeaddrinfo(result);
                closesocket(ListenSocket);
                WSACleanup();
                return 1;
        }
       
        freeaddrinfo(result);
        if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
                printf("Listen failed with error: %ld\n", WSAGetLastError());
                closesocket(ListenSocket);
                WSACleanup();
                return 1;
        }
        for (;;)
        {
                //creating a temp socket for accepting a connction
                SOCKET ClientSocket;
                // Accept a client socket
                ClientSocket = accept(ListenSocket, NULL, NULL);
                if (ClientSocket == INVALID_SOCKET) {
                        printf("accept failed: %d\n", WSAGetLastError());
                        closesocket(ListenSocket);
                        WSACleanup();
                        return 1;
                }
                else
                {

                        myThreads[ClientCount] = std::thread(callThread,ClientSocket,ClientCount);
                        ClientCount++;

                        printf("normal count: %d\n", ClientCount);

                        if (ClientCount == 1)
                        {
                                cout << "Waiting for another Client to connect" << endl;
                        }
                        /*if (ClientCount >= 2)
                        {
                                cout << "Game" << type << "in progress" << endl;
                        }*/
                       
                }
        }

        // shutdown the connection since we're done
        iResult = shutdown(ClientSocket, SD_SEND);
        if (iResult == SOCKET_ERROR) {
                printf("shutdown failed with error: %d\n", WSAGetLastError());
                closesocket(ClientSocket);
                WSACleanup();
                return 1;
        }

        // cleanup
        closesocket(ClientSocket);
        WSACleanup();
        system("PAUSE");
        return 0;
}


number of controls in mfc dialog vs2012

$
0
0
In a mfc app. , after added a control, getting the message number of controls is more than 255, some of the controls may not display correctly. What can be without removing any control?. It is not so easy to change its design at this stage.

Traveling Salesman Problem C++ Code Issue

$
0
0
The following code is an algorithm I designed to solve the Traveling Salesman Problem. I am using a Nearest Neighbor Algorithm to find an optimal path and cost of a 5 city tour. When I run the program, the cost calculation is correct. However, the optimal path output is always “154321”. This is the output even if I change the distances between the cities in the cost matrix. How do I configure the code to make the optimal path output change when the distances between the cities are changed in the cost matrix?

Code:

#include <iostream>
using namespace std;

//Global definitions
int costMatrix[5][5];
int vistedCities[5];
int numCity = 5;
int cost = 0;

//Function prototypes
int tsp(int);
void minCost(int);

//Main functions
int main()
{

        int i;
        int j;

        //Enter distance between cities
        cout << "\n\nEnter distance between cities into matrix...\n";
        for (i = 0; i < numCity; i++)
        {
                cout << "\nEnter " << numCity << " elements in Row[" << i + 1 << "]\n";
                for (j = 0; j < numCity; j++)
                        cin >> costMatrix[i][j];
        }

        //Display matrix of distances between cities
        cout << "\nDistances entered into cost matrix:\n";
        for (i = 0; i < numCity; i++)
        {
                cout << endl;
                for (j = 0; j < numCity; j++)
                {
                        cout << costMatrix[i][j] << " ";
                }
        }

        //Display results
        cout << "\n\n Optimum Path: \t ";
        minCost(0);
        cout << "\n Minimum Cost: \t";
        cout << cost;

        system("pause");
        return 0;
}

//Function to determine minimum cost
void minCost(int city)
{
        int nearestCity;
        vistedCities[city] = 1;

        cout << city + 1;
        nearestCity = tsp(city);

        if (nearestCity == 999)
        {
                nearestCity = 0;
                cout << nearestCity + 1;
                cost = cost + costMatrix[city][nearestCity];
                return;
        }
        minCost(nearestCity);
}

//Funciton for TSP algorithm
int tsp(int city1)
{
        int counter;
        int nearestCity = 999;
        int mini = 999;
        int temp;

        for (counter = 0; counter < numCity; counter++)
        {
                if ((costMatrix[city1][counter] != 0) && (vistedCities[counter] == 0))
                {
                        if (costMatrix[city1][counter] < mini)
                        {
                                mini = costMatrix[counter][0] + costMatrix[city1][counter];
                        }
                        temp = costMatrix[city1][counter];
                        nearestCity = counter;
                }
        }
        if (mini != 999)
                cost = cost + temp;

        return nearestCity;
}

Support_needed_regarding_failure_"doest not name a type"

$
0
0
Hello,

could you support me in the failures of this task, I have included also the actual failures in Word-Doc.

Thank you in advance,

Code:

/*######################################################
    Einsendeaufgabe 5.2
###################################################### */

/* ##################################
    Doppelt verkettete Liste
  ################################## */

#include <iostream>
using namespace std;

//Die Struktur für die Listenelemente
struct listenelement
    {
    string daten;
    listenelement* next;
    listenelement* last;
    };

listenelement* listenanfang;
listenelement* listenende;
listenelement* hilfszeiger;


//Eine Funktion zum Anhängen von Elementen an die Liste
void anhaengen(string datenneu)
    {
    hilfszeiger = listenanfang;
    while (hilfszeiger->next != nullptr)
          hilfszeiger = hilfszeiger->next;
    }

    hilfszeiger->next = new(listenelement);
    listenelement* bisherLetzter = hilfszeiger;
    hilfszeiger = hilfszeiger->next;

    strcpy(hilfszeiger->daten,datenneu);
    hilfszeiger->next = NULL;
    hilfszeiger->last = bisherLetzter;
    listenende = hilfszeiger;
}


//Eine Funktion zum Ausgeben aller Elemente
void ausgeben()
    {
    hilfszeiger = listenanfang;
    cout << hilfszeiger->daten << '\n';

    while (hilfszeiger->next != nullptr)
        {
        hilfszeiger = hilfszeiger->next;
        cout << hilfszeiger->daten << '\n';
        }
    }


void ausgaberueckwaerts() {

        hilfszeiger = listenende;

        cout <<hilfszeiger->daten<<"\n";

        while (hilfszeiger->last != NULL) {

        hilfszeiger = hilfszeiger->last;
        cout << hilfszeiger->daten << "\n";
        }

}

void initialisieren() {

        listenanfang = new(listenelement);
        listenanfang->next = NULL;
        listenanfang->last = NULL;
        listenende = listenanfang;
        strcpy(listenanfang->daten,"Element 0");
}

//die Liste leeren und Speicher freigeben
void ende()
    {
    while (listenanfang != nullptr)
        {
        hilfszeiger = listenanfang;
        listenanfang = listenanfang->next;
        delete(hilfszeiger);
        }
    }

int main ()
    {
    initialisieren();
    anhaengen("Element 1");
    anhaengen("Element 2");
    anhaengen("Element 3");
    ausgeben();
    ausgaberueckwaerts();
    ende();

    return 0;
    }

Attached Files

Need help debugging

$
0
0
I have been constantly been trying to be debug this game and have failed inevitably,
Code:

Code:

#include <iostream>
#include <cmath>
#include <time.h>
#include <cstdlib>
using namespace std;
// starting main function
#include <iostream>
#include <fstream>
#include <iomanip>
#include <ctime>
#include <string>

using namespace std;

void mainMenu();
int rollDie();
void pigDice();
int pd_turn(string name);
void save();
void selectionSort();
int readData;
void RockpaperScissors();

int main()
{
        //srand(time(0));
        mainMenu();
        return 0;
}

void mainMenu()
{
        char choice = 'z';

        while (choice != 'q') {
                cout << "Menu\n"
                        << "a) Pig Dice Game\n"
                        << "b) Roll Die\n"
                        << "c) Game 2\n"
                        << "d) Stats menu\n"
                        << "q) quit\n"
                        << "Please enter a menu selection: ";
                cin >> choice;

                switch (choice)
                {
                case 'a':
                case 'A':
                        break;
                case 'b':
                case 'B':
                        cout << "\nYou rolled a " << rollDie() << ".\n\n";
                        break;
                case 'c':
                case 'C':
                        break;
                case 'd':
                case 'D':
                        break;
                case 'q':
                case 'Q':
                        choice = 'q';
                        break;
                default:
                        cout << "Incorrect input please try again.\n";
                } //end of switch
        }  //end of while
}


void pigDice()  //function to control the game play for pigDice
{
        int player1_score, player2_score;
        char choice='z';
        string player1, player2;

        //get name of players
        cout << "Player1 enter your name: ";
        cin >> player1;
        cout << "Player2 enter your name: ";
        cin >> player2;

        //players roll to determine the order of play.  Place in a loop in case of tie.
        while (choice != 'n')
        {
                cout << "\nDetermining the order of play. Player1 roll the dice. \n";
                system("pause");
                player1_score = rollDie();
                cout << "\nPlayer1 you rolled a " << player1_score << ".\n";
                cout << "\nPlayer2 roll the dice.\n";
                system("pause");
                player2_score = rollDie();
                cout << "\nPlayer2 you rolled a " << player2_score << ".\n";

                //establish who plays 1st and who plays 2nd
                if (player1_score < player2_score) {
                        player1_score = 0;
                        player2_score = 1;
                        cout << player1 << " you play first. " << player2 << " you go second.\n";
                        choice = 'n';  // terminate this loop
                }
                else if (player2_score < player1_score) {
                        player2_score = 0;
                        player1_score = 1;
                        cout << player2 << " you play first. " << player1 << " you go second.\n";
                        choice = 'n';  //terminate this loop
                }
                else
                        cout << "\nIt's a tie.  You both roll a " << player1_score << ".\n"
                        << "Please try again.\n";
        }//end of while

        //first player to play plays - play function
        if (player1_score == 0)
                player1_score = pd_turn();
        else
                player2_score = pd_turn();

        //check if score is >50.  if it is then we have a roll off
        //if we have a roll off, second player must roll until win or lose
        //determine winner and offer to save
        //if we do not have a roll off, loop,
                //second to play plays, keep score, check if they won. if they won offer to save*
                //first to play plays, keep score, check if they won.  If they won offer to save*
         

}
int rollDie()
{
        int die;
       
        srand(time(0));
        die = rand() % 6 + 1;

        return die;
}

int pd_turn() //function stub
{
            int die, score = 0; die = 0;
        char choice = 'z';
        system("pause");
        system("cls");
        cout << "\n\n" << name << " it is your turn.\n\nYou may roll the dice until you choose to stop.\n"
                << "Once you choose to stop your score for this turn\nwill be added to your overall score. "
                << "If you roll a 1 \nthen you lose your turn and all the points for this.\n\n";
        while (choice != 'n')
        {
                cout << "\nRoll the dice.\n";
                system("pause");
                die = rollDie();
                cout << "\nYou rolled a " << die << ".\n";
                if (die == 1) {
                        cout << "\nSorry you rolled a " << die << " and so you lose your turn.\nYou get 0 points this turn.\n";
                        score = 0;
                        return score;


                }
                else {
                        score += die;
                        cout << "\nYour current points for this turn is : " << score << endl
                                << "\nWould you like to roll again or quit? Enter y to continue and n to quit: ";
                        cin >> choice;
                        //system("cls");
                        return score;
                }
        }
}

void save(string winner, int score)
{
        const int SIZE = 10;
        string users[SIZE];
        int scores[SIZE], deleteRecord, index, readData,displayStats,spaceAvailable,writedata_pd;
        char choice = 'z';
        bool spaceAvailable = false; //used to check if need to delete

        for (int i = 0; i < SIZE; i++) {  //init arrays
                users[i] = "no user";
                scores[i] = -10;
        }
        cout << "\n\n" << winner << " do you wish to save your score? (Y/N) "; //give user option to save or not
        cin >> choice;
        if (choice == 'y' || choice == 'Y'){
                readData(users, scores, SIZE); //call the readdata function (opens file and read data into arrays)
                selectionSort(users, scores, SIZE);
                displayStats(users, scores, SIZE); //call your display function to display your arrays
                for (int i = 0; i<SIZE; i++) { //check if arrays has space or not
                        if (users[i] == "no user" && spaceAvailable == false) { //if there is space assign winner loser
                                spacecAvailable = true;
                                index = i;
                }
        }
        if (spaceAvailable == true) {// if there is no space, please assign a winner and score
                users[index] = winner;
                scores[index] = score;
        }
        else {  //if the array does not have space
                cout << "\n\n Maximum saved users reached." //ask the user if they want to overwrite a user
                        << " Do you wish to quit(Q) without saving or replace(R) a user> (Q/R) :";
                cin >> choice;
                if (choice == 'r' || choice == 'R') {//if the user choices to overwrite
                        displayStats(users, score, SIZE);
                        writedata_pd(users, score, SIZE);
                        cout << "Saving completed! Exiting Pig dice game. Please play again.\n";
                        system("pause");
                }
                else //end if user choose yes to save
                        cout << "\nThanks for playing. Goodbye...";
        } //end of save
       
        void selectionSort(string list[], int score[], int length)
        {
                int index, smallestIndex, location, temp;
                string stempl //used to swap the usernames which are strings and temp is used for scores

                        for (index = 0; index<length - 1; index++) {

                                smallestInDEX = index;
                                //sort by score rather than list
                                for (location = index; location < length; location++)
                                        if (score[location]<score[smallestIndex])
                                                smallestIndex = location;

                                //do this for both score and list to process the arrays in parallel
                                temp = score[smallestIndex];  //swaps the values for the score array
                                score[smallestIndex] = score[index];
                                score[index] = temp;

                                stemp = list[smallestIndex]; //swap the values for the list/ users array
                                list[smallestIndex] = list[index];
                                list[index] = stemp;
                        }
        }//end sort function
       
                void readData(String list[], int score[], int SIZE)
        {
                ifsream indata; //declare input stream variable
                indata.open("userdata.txt"); //open input stream and associate with input file
                int location = 0; //used to iterate through an array
                while (!indata.eof()) //read data
                {
                        if (location < SIZE)  //in case my file gets corrupted and ends up with more than length  records
                                indata >> list[location] >> score[location];
                        location++;
                }//end of while
                indata.close();
        }
       
        void writedata_pd(string users[], int scores[], int SIZE)
        {
                ofstream outdata;
                outdata.open("userdata.txt");
                for (int i = 0; i < SIZE; i++)
                        if (users[i] != "no user")
                                outdata << user[i] << " " << scores[i] << endl;
                outdata.close();
        }
       
                void displayStats(string user[], int scores[], int SIZE)
        {
                system("cls");
                //display the heading
                cout << "Pig Dice Scoreboard\n\n"
                        << "ID " << setw(20) << left << "User" << "Score\n"; // << setw(28) << setfill('_') << "\n";

                for (int i = SIZE - 1; i >= 0; i)// display the array
                        cout << setw(3)<, i + 1 << " "<setw(20) << left << users[i] << scores[i]<, "\n";
        }
       
        //
void RockpaperScissors()  //function to control the game play for Rockpapers
{
    char ch;
    // set up my variables for the scores
    int win = 0;
    int tie = 0;
    int lose = 0;
    // start of game loop, the loop will run untill ch == n
    do{
    int choice;
    // Fancy printed title, well as fancy as I can do.
    cout << "--------------------------------------" << endl;
    cout << "-- Lets play Rock, Paper, Scissors! --" << endl;
    cout << "--------------------------------------" << endl;
    // Ask the player to choose Rock, Paper, Scissors
    cout << "Press 1 for Rock, 2 for Paper, 3 for Scissors:" << endl;
    cin >> choice;
    // gets a random number between 1 and 3 and tell the player what was chosen
    int ai = rand() % 3 + 1;
    cout <<  "The computer chose: " << ai << endl;
    // starts possible outcome sequence in rock paper scissors there are 9 possible out comes 3 wins 3 ties and 3 losses.
    if(choice == 1 && ai == 1){
        cout << "Rock meets Rock its a tie!" << endl;
        tie++;
        }
    else if(choice ==1 && ai== 2){
        cout << "Rock is covered by Paper the computer wins!." << endl;
        lose++;
        }
    else if(choice == 1 && ai == 3){
        cout << "Rock crushes Scissors you win!" << endl;
        win++;
        }
    else if(choice == 2 && ai == 1){
        cout << "Paper covers Rock you win!" << endl;
        win++;
        }
    else if(choice == 2 && ai == 2){
        cout << "Paper meets Paper its a tie!" << endl;
        tie++;
        }
    else if(choice == 2 && ai == 3){
        cout << "Paper is cut by Scissors the computer wins!" << endl;
        lose++;
        }
    else if( choice == 3 && ai == 1){
        cout << "Scissors are crushed by Rock computer wins!" << endl;
        lose++;
        }
    else if( choice == 3 && ai == 2){
        cout << "Scissors cuts Paper you win!" << endl;
        win++;
        }
    else if(choice == 3 && ai == 3){
        cout << "Scissors meet Scissors its a tie!" << endl;
        tie++;
        }
        // this is what happens if the player doesn't hit 1 2 or 3
    else{
        cout << "You didn't select 1, 2, or 3" << endl;
        }
        // displays your score so far and asks if you want to play again then clears screen
        cout << "Wins: " << win << endl;
        cout << "Ties:" << tie << endl;
        cout << "Losses:" << lose << endl;
        cout << "Would you like to play again? Y/N" << endl;
        cin >> ch;
        system("CLS");
        }while(ch == 'Y' || ch == 'y');
   
}

:confused:

Hi . Sorry for posting the full code but I'm still a beginner and need ur help .

$
0
0
Code: --------- #include using namespace std; void readValues (int & ,int &); // 2 values A and B int factorial (int &); // A int divCount (int); // A void evSum (int &, int &,long); // A and B and I should have the long sum int main () { int A,B; int choice; do { cout<<"Enter a positive integer A :"<>A; cout<<"Enter a positive integer B :"<>B; } while (A<=0 || B<=0 || A>B); do { cout<<"Choose a computation from the following menu :" <<"1- Compute sum of the Factorials of "<>choice; switch (choice) { case 1 : { cout<<"The following program computes the sum of factorials of "<=a,i<=b,i++) if (i % 2 == 0) int evSum = 0; // I don't know if I should use "evsum" from main or "evSum" evSum += i; return evSum; } ---------

I need help with writing a program in C++ (I'm still a newbie)

$
0
0
Define class for geometric shape triangle. The member variables of the class are the lenghts of the sides of the 3 sides of the triangle. The member functions have to include: constructor that checks if the entered values are sides of a triangle, destructor, fuction for calculating and output the face of the triangle. To create a main function which creates an object from the class and tests the constructor and the destructor. ( The second sentence doesn't make much sense though, because my English is broken :cry: :cry: .Thanks in advance )

Help with Coding (Newbie)

$
0
0
Hi Guys, Need help with this code. Using codeblocks and getting error that the template is not being recognised. Code is as follows: Code: --------- #include #include #include #include #include #include void menu(vector& windlog); void readFile(ifstream& inputFile, vector& windlog); void averageWind(int monthNum, vector& windlog); int main() { vector windlog; ifstream inputFile("MetData-31-3.csv"); if(!inputFile) return -1; readFile(inputFile, windlog); menu(windlog); return 0; } void readFile(std::ifstream& inputFile, std::vector& windlog) { float tempSpeed; int timeIndex, windSpeedIndex, radiationIndex; int columns = 18, field = 0; std::string tempDate, tempTime; std::string headers[20]; std::string nStream; for(int i = 0; i < columns -1; i++) { getline(inputFile, headers[i], ','); if(headers[i] == "WAST") timeIndex = i; if(headers[i] == "S") windSpeedIndex = i; if(headers[i] == "SR") radiationIndex = i; } getline(inputFile, headers[17]); if(inputFile) { std::string token; std::stringstream iss, dateStream; while(getline(inputFile, nStream)) { iss << nStream; while(getline(iss, token, ',')) { if(field == timeIndex) { dateStream << token; getline(dateStream, tempDate, ' '); getline(dateStream, tempTime); } if(field == windSpeedIndex) { tempSpeed = std::atof(token.c_str()); } field++; } field = 0; iss.clear(); dateStream.clear(); WindData windSpeed(tempDate, tempTime, tempSpeed); windlog.push_back(windSpeed); windSpeed.print(); } std::cout << "Vector Size: " << windlog.size() << std::endl; } } void averageWind(int yearNum, std::vector& windlog) { std::string month[12] = {"January", "February", "March", "April", "May", "June", "July", "August" "September", "October", "November", "December"}; int monthCount = 0, monthNum[12] = {0}, monthAverage[12] = {0}; int dayCount[12] = {0}, totalWindSpeed[12] = {0}, totalRadiation[12] = {0}, mWindAverage[12] = {0}; for (WindData& windData : windlog) { if (windData.getYear() == yearNum) { int i = windData.getMonth() - 1; totalWindSpeed[i] += windData.getSpeed(); dayCount[i]++; } } std::cout << "Wind Speed: " << totalWindSpeed[i] << std::endl; std::cout << "Day Count: " << dayCount[i] << std::endl; for (int i = 0; i < 12; i++) { mWindAverate[i] = totalWindSpeed[i] / dayCount[i]; } std::cout << mWindAverage[i]; std::cout << month[i]; } void menu(std::vector& windlog) { int option = 0; while(option != 5) { std::cout << "Menu:" << std::endl; std::cout << "1: \tPrint the maximum wind speed for a specified month & year" << std::endl; std::cout << "2: \tPrint the average wind speed for each month of a specified year" << std::endl; std::cout << "3: \tPrint the total solar radiation for each month of a specified year" << std::endl; std::cout << "4: \tAverage wind speed & solar radiation for each month of a specified year\n\tSaved to file." << std::endl; std::cout << "5: \tExit the program.\n\n" << std::endl; std::cin >> option; switch(option) { case 1: break; case 2: int year; std::cout << "Please enter a year" << std::endl; std::cin >> year; averageWind(year,windlog); break; case 3: break; case 4: break; case 5: std::cout << "Exiting..." << std::endl; break; } } } --------- *winddata.h:* Code: --------- #ifndef WINDDATA_H #define WINDDATA_H using namespace std; template class vector{ public: /**default constructor*/ vector(int size = 100000); vector(Vector& otherList); ~vector(); /**data members*/ private: WindData *list ; int length; int maxSize; }; /** implementation of template class*/ template vector::vector(int size) { maxSize = listSize; length = 0; list = new WindData[maxSize]; } template vector::~vector() { delete[] list; } /**end of class*/ #endif ---------

[RESOLVED] Hi . Sorry for posting the full code but I'm still a beginner and need ur help .

$
0
0
Code: --------- #include using namespace std; void readValues (int & ,int &); // 2 values A and B int factorial (int &); // A int divCount (int); // A void evSum (int &, int &,long); // A and B and I should have the long sum int main () { int A,B; int choice; do { cout<<"Enter a positive integer A :"<>A; cout<<"Enter a positive integer B :"<>B; } while (A<=0 || B<=0 || A>B); do { cout<<"Choose a computation from the following menu :" <<"1- Compute sum of the Factorials of "<>choice; switch (choice) { case 1 : { cout<<"The following program computes the sum of factorials of "<=a,i<=b,i++) if (i % 2 == 0) int evSum = 0; // I don't know if I should use "evsum" from main or "evSum" evSum += i; return evSum; } ---------

[RESOLVED] I need help with writing a program in C++ (I'm still a newbie)

$
0
0
Define class for geometric shape triangle. The member variables of the class are the lenghts of the sides of the 3 sides of the triangle. The member functions have to include: constructor that checks if the entered values are sides of a triangle, destructor, fuction for calculating and output the face of the triangle. To create a main function which creates an object from the class and tests the constructor and the destructor. ( The second sentence doesn't make much sense though, because my English is broken :cry: :cry: .Thanks in advance )

debugger break point jumps

$
0
0
In my MFC, when I try to set a break point at an imported function, the break point jumps to the next line. I updated the .pdb, still same. This does not happen with all imported functions. IDE:VS2012.

[RESOLVED] GetDlgItemText and Multithreading

$
0
0
So I have been trying to implement the concept of multithreading to an MFC application I am making. I used the method suggested here (https://www.codeproject.com/Articles/2459/Using-AfxBeginThread-with-class-member-controlling). It works fine but I am having an issue with using data given by the user while the thread is working. I'll explain. I am making a simple GUI to send and receive data over a serial port. So the data in IDC_SEND is user-input, and is then sent through the serial port. I am using the WINAPI definition of GetDlgItemText, but since the controlling function for AfxBeginThread is defined as a static function I cannot do this. So I tried ::GetDlgItemText, but that calls the CWnd definition which takes one or three or four(?) arguments. So ::GetDlgItemText(IDC_SEND, CString text) doesn't work. This problem continues for SetDlgItemText too. I have tried getting the data outside my controlling function, but since it is defined to return a UINT type, I cannot get the received data out. The relevant code Code: --------- void CCommTest2Dlg::OnButton() { THREADSTRUCT *_param = new THREADSTRUCT; _param->_this = this; AfxBeginThread (StartThread, _param); } UINT CCommTest2Dlg::StartThread(LPVOID param) { THREADSTRUCT* ts = (THREADSTRUCT*)param; AfxMessageBox ("Thread is started!"); //Opened Serial Port //Writing data from Editbox CString text; ::GetDlgItemText(IDC_SEND,text);//********ERROR HERE!! serial.Write(text); //At Receiver port data is wriiten into CString a. CString a; ::SetDlgItemText( IDC_RECV, a);//Apparently this calls the SetDlgItemText from the CWnd class, and not the Windows API that takes more than one argument. AfxMessageBox ((LPCTSTR)a);//This works, but I need the data in the EditBox. //Closing Ports delete ts; //Edit 1 return 1;} --------- A few definitions: Code: --------- static UINT StartThread (LPVOID param); //structure for passing to the controlling function typedef struct THREADSTRUCT { CCommTest2Dlg* _this; } THREADSTRUCT; UINT StartThread(void); --------- Any thoughts? PS: Also Edit 1 at the end was added by me as I read that this implementation could result in memory leaks. Does it look like the addition might have fixed that?

Recommend a C or C++ code to send a basic email using the SMTP protocol

$
0
0
I have seen many tutorials with confusing functions that are difficult to translate and understand. I am also not looking for a GUI implementation. I am looking for a basic C or C++ program that has basic(C-file) libraries and not (.exe libraries) to include, that can send a email with a SMTP or equivalent protocol. The program should except simple parameters like from-email, to-email, email-subject, email-body text, host, email-username, email-password. I have experience with SMTP with Java programming, here is example link that uses few library imports that are also easy to find online to download, the link is: https://www.tutorialspoint.com/java/java_sending_email.htm . Any help will be appreciated with C or C++ programming code.

Project

$
0
0
I have to complete a project... and i need help of any one... i dont know abou it... Publishwithus *FunctionalSpecifications:* Youneedtocreatetherequiredapplicationandnecessaryservicetoimplementthe followingfunctionalrequirements. 1.Publisherskeepdataabouttheirbooksinacloudhostedquery-ableMongo DBdatabase.Soassumeyouhavethedatainthedb.Createawebserviceto allowqueryingofthisdata.Serviceresponsibleforinserting,updatingand deletingrecordfromMONGOdb. 2.Universitylibrariesshouldbeabletoallowtheirmemberstoregister,login, andchecktheirpreviousdemandsusingawebapplication. 3.Thisapplicationshouldalsoallowtosearchthepublishers’dataandshould letmembersplacedemandsforbookswiththeirlibraries. NonFunctionalSpecifications: 1.Createawebservicearchitecture.Thecomponentsshouldbelooselycoupled andshouldoperatefairlyindependently. 2.Webapplicationshouldallowuserstoregister,authenticateandmaintain theirlistofbookdemands. Steptofallow: 1.Installvisualstudio2013orhigherversion. 2.Installmongodbonyourlocalmachine.Pleaserefertobelowlinkfor download(https://www.mongodb.com/download-center) 3.CreateWebApiusingMVC5templateandconnectwithMongoDB. 4.CreateWebapplicationtocommunicatewithWebAPI.Makesureyour webapplicationisseparatefromyourwebapiproject. 5.UserSignuppage,Signinpage,Publisherpage,Bookssearchpageand booksadddeletefunctionalitypagesarecorefunctionalityofthis application. Deadlineofthisapplicationisoneweek.Afterthisblueprintwedecidetogoforbetaversion. MakesureyouhostthisapplicationonyourdevmachinesoIcantakedemoonreal environment.Initialbudgetforthisapplicationis250$(NZ)butaftersuccessfulcompletionof thisblueprintwemovetoonhourlybasesaswedonepreviously.

Need help with my curent code and the scenario of the code

$
0
0
so far i have done; Code: --------- #include #include using namespace std: int main() { int SName( int james, int mary, int dan) cout<< "Please enter you staff name : " ; cin>> james; cout<< "Please enter you staff name : " ; cin>> mary; cout<< "Please enter you staff name : " ; cin>> dan; } --------- i started of with this but i dont know if it is correct this is advanced level code and i want to try it out but i am very stuck. i dont know if it is right a little help please the scenario of my code is this; How the program should work : When the cinema sales staff start the program they will be asked to enter their staff name, the date and which of two films the customer wants to see. The films are Deadpool and Goosebumps Cinema ticket prices are charged as follows : Ticket Prices Adult £10.30 Senior citizen 20% reduction Children half the Adult price A customer’s booking for a particular show can be for a number of tickets, at different prices (e.g. one adult and two children, or one adult and one senior citizen etc.). The maximum number of customers in the cinema is 60 so the tickets purchased must be validated . Calculate the cost of the number of tickets purchased by the customer The screen should be cleared and then a customer receipt must be displayed, showing the Cinema name, Film seen , staff name, number of tickets purchased in each category, the total cost in each category and the total to be paid. At the end of the day, after the sale of tickets to the last customer, the program should calculate and display the cinemas’ total sales income for both shows

Overload function error

$
0
0
Now I just have issue figuring out how to add the quantities, as in if I make the same selection more than once it only calculates one. Code: --------- // //Preprocessor Directives #include #include #include #include using namespace std; //Menu Structure struct menuOptions { int quantity; double price; string description; }; //prototype void displayMenu(menuOptions menu[], int size); void getData(menuOptions menu[], int &size); void printCheck(menuOptions menu[], int size); //constants const int max = 8; const double taxes = 0.05; // main function int main() { menuOptions menu[max]; int size = 0; getData(menu, size); displayMenu(menu, size); printCheck(menu, size); system("pause"); // exit main return 0; } //getting the data in to array void getData(menuOptions menu[], int &size) { menu[0].description = "Plain Egg"; menu[0].price = 1.45; menu[0].quantity = 0; menu[1].description = "Bacon and Egg"; menu[1].price = 2.45; menu[1].quantity = 0; menu[2].description = "Muffin"; menu[2].price = 0.99; menu[2].quantity = 0; menu[3].description = "French Toast"; menu[3].price = 1.99; menu[3].quantity = 0; menu[4].description = "Fruit Basket"; menu[4].price = 2.49; menu[4].quantity = 0; menu[5].description = "Cereal"; menu[5].price = 0.69; menu[5].quantity = 0; menu[6].description = "Coffee"; menu[6].price = 0.50; menu[6].quantity = 0; menu[7].description = "Tea"; menu[7].price = 0.75; menu[7].quantity = 0; size = 8; } //display menu and tell user what to do void displayMenu(menuOptions menu[], int size) { cout << "Welcome to Johnny's Restaurant" << endl; cout << setw(20) << "Johnny's Menu" << endl; for (int i = 0; i < size; i++) { cout << (i + 1) << ". " << left << setw(21) << menu[i].description << "$" << setw(6) << setprecision(2) << fixed << menu[i].price << endl; } cout << "------------------------------" << endl; int number; int quantity; cout << "\nSelect your item 1-8. Press 9 when you are finished: "; cin >> number; while (number != 9) { if (number >= 1 && number <= 8) { menu[number -1].quantity = 1; } else { cout << "Invalid Option! Item selection 1-8, and press 9 to finish your order!" << endl; } cout << "Select your item 1-8. Press 9 when you are finished: "; cin >> number; } } //calc and print check void printCheck(menuOptions menu[], int size) { double totalPrice = 0; double totalTax = 0; cout << "\nYour Check is:" << endl; cout << endl << "Welcome to Johnny's Restaurant" << endl; for (int i = 0; i < size; i++) { if (menu[i].quantity > 0) { cout << left << setw(2) <

MFCButton control images and differing screen resolutions

$
0
0
Hey Gurus! I have an application where I use CMFCButton controls. Using SetImage() I have put an icon to the left of the text in the button. It looks great and works well. Recently I installed my application onto a laptop with a different screen resolution, and consequently all the images next to the text in the buttons are now displayed smaller than I was expecting. I also have the same issue that uses an icon in a picture control. It makes sense of course, differing screen resolutions with set width and height icons are not going to display the same on each screen. Is there something in the API to allow for this type of issue, and if not, how do I go about doing it manually? Thanks so much in advance. Steve Q. :-)

analog outputs?

$
0
0
Hello I shall write a Program that shall communicate with an external device which has analog input values. It has a connector with 5 pins and depending on which pin is active it is doing something. I was thinking about using the RS232 connection and connection each RS232 PIN with the Pin from the device and then just activate each pin as I need it. Is this possible? If not which other way can I choose?

In mfc MDI project the onfilenew restores the existing fullscreen MDI child.

$
0
0
Dear All, I have a MFC MDI project where in on start a maximised MDI child window is created. Later the user can create more MDI children. It is observed that when more children (12 of them) are created by OnFileNew() the existing maximized MDI child is restored and briefly we see the restored mdi child window on screen. Is there a way to stop the restoring of the existing maximized MDI child window. I have got screenshot which shows the problem. Attachment 34849 (http://forums.codeguru.com/attachment.php?attachmentid=34849) Thanks and Regards, Rakesh What I have tried: I have tried creating the new children in hide mode (SW_HIDE). It didnt work. I tried creating the new children in very small size and outside the mdi main frame client area. I have tried putting the existing window on top ( Hide Copy Code pAnimView->SetWindowPos(&CWnd::wndTop, 0, 0, 0, 0,SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); ) and then making calls to OnFileNew(); Nothing worked.

How to share CCriticalSection between modules

$
0
0
I am in a situation where I need to synchronize two threads in two different dll modules synchronize around the same CCriticalSection object. I can define the CCriticalSection in one module but how can ther module access it? I would need to place the following call in corresonding function in each thread. Code: --------- CSingleLock lock( &theCriticalSection, TRUE); --------- I tried using this approach (https://msdn.microsoft.com/en-us/library/aa270058(v=vs.60).aspx) but no luck. I tested with a simple int variable but it doesn't recognize it in the other dll (although it buids). Code: --------- #pragma data_seg("shared") __declspec(dllexport) CCriticalSection theCriticalSection; __declspec(dllexport) int number = 7; #pragma data_seg() #pragma comment(linker, "/section:shared,RWS") --------- I declare this as following in the dll where I want to use it: __declspec(dllimport) CCriticalSection theCriticalSection; __declspec(dllimport) int number; Later in the function TRACE("number = %s", number ); asserts because it can't apparently link/recognize to `number`variable.
Viewing all 3027 articles
Browse latest View live