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

I need help with this program

$
0
0
Please help me fix this code.
.
.

What I want to do is create a file that will ask the user to enter his info,
then store it in a text file
The screen will ask the user if he wants to update his info. if he says yes
then the screen will be cleared and the old info will be printed on the screen. The user will enter his new info that will be stored in a new file.
My problem is that once the user finishes entering his input the program just closes D: and the rest of the program won't run.
Thanks for your help
Code:




int main()
{
        string ans;

        ofstream Xfile("original.txt");

        cout <<"Enter your name and address please"<<endl;

        cout<<"Press Ctrl+Z+Enter when you are done"<<endl;

        string name_and_street;
       
        while (cin >> name_and_street){
                       
                Xfile << name_and_street << endl;
        system("cls");
        }
       
        cout <<"Would you like to update your address?(yes/no);";
        cin>>ans;
        while(ans=="yes"){

       
}


How to determine cross platform type during file save?

$
0
0
Hello,
I am overriding OnSaveDocument in my MFC document class to strip out the carriage returns when saving my app's document to a UNIX file system but not when the user is saving a file to a Windows file system.

Is there a way to determine if the lpszPathName in OnSaveDocument(LPCTSTR lpszPathName) is a UNIX or Windows file system?

Note, I want to avoid hard coding server names and I want to avoid overriding the FileSave dialog and forcing the user to select Windows or UNIX.


Thanks.

FindNextFile() Looping and Backwards ?

$
0
0
Hi guys, I'm using FindFirstFile() and FindNextFile() to go through all the files in a directory, I want to be able to go backwards and also loop at the beginning and end, like this:

001.txt
002.txt
003.txt
004.txt

...if I am at 003.txt and select back command it should go to 002.txt, if I am at 001.txt and select back command it should go to 004.txt.

For forward looping I can start the process over again with FindFirstFile() but I am not sure if that is smart.

I know that I can store all the filenames in an array but some directories may have 10k file counts so maybe that's not a good idea ?

Thank you.

Run-Time Check Failure #3 - The variable is being used without being initialized

$
0
0
Under visual studio, this is a typical run time error,
Code:

void func(int x)
{
    x = 3;
}

int main()
{
    int x;

    func(x);
}

When x is passed to the function func, it is not initialized. But my question is that why it should be an error? On the other hand, if I change the definition of func a little bit like this,
Code:

void func(int& x)
{
    *x = 3;
}

int main()
{
    int x;

    func(&x);
}

Now in main, x is still not initialized, but this time there isn't a run time error like "the variable is being used without being initialized. Why? Thanks.

GetOpenFileName() Positioning Problem

$
0
0
Hi guys,

When I call GetOpenFileName() it opens in the top-left corner for a split-second before appearing in the center of the screen.

I tried different parameters for OPENFILENAME.hwndOwner and OPENFILENAME.hInstance but it didn't help.

I noticed that if I enable a hook with the flag OFN_ENABLEHOOK it displays fine but it's an older style dialog box, I want the Win 8 one that I get without the hook flag.

What should I do ?

Thanks.

Solving "RangeChecks instrumentation code detected an out of range array access"

$
0
0
Firstly, I am using Visual Studio 2013

I have a project written in VB6 and VC++ 6.0 which I am porting over to VB.NET and VC++.

Right at the heart of everything is a routine written in VC++ which runs to 1,400 lines of native code and processes a whole raft of arrays which are transferred from VB.NET. This routine may run for days during which time it literally runs through trillions of times (ie 10 ^ 12 ). If I split it into smaller routines there is a huge time penalty. Been there - tried that.

Amazingly, I have got this working in principle (I had expected to spend months debugging it but it worked almost immediately). One of the problems is/was that if you referred to a VB6 array in VC++ 6.0 you have to reverse it - so, for example

Code:

' VB6
Public dblObjectArrayGP(OBJECTS_MAX, PROPERTIES_MAX, TRIALS_MAX, STEPS_MAX) As Double

'In VC++ 6.0 refer to it as
dblObjectArrayGP[][TRIALS_MAX + 1][PROPERTIES_MAX + 1][OBJECTS_MAX + 1];

But it worked. Now in VB.NET - VC++ , Microsoft have arranged things so that you do NOT have to reverse arrays anymore. Which means that I have had to to reverse hundreds of array references (the law of unintended consequences). Hence my amazement when it worked in principle.

I have spelled all this out because I know that people will reply along the lines of:
"Why not write it all in VB.NET?"
"Why not break it into many smaller routines?"
"You should use Vectors not arrays" etc etc

and that is not helpful - this is a conversion job not a new project (if it were I would do lots of things differently). The original was written over 25 years and is at the limits of my ability to hold it together (ie it is hideously complicated). Original version(s) were written in QB4.5 and Quick C.

Now, when it runs maybe 50 times or so it fails and I get this message:

"Unhandled exception at 0x77B76767 (SafariPark.dll) in MOPEKS.exe: RangeChecks instrumentation code detected an out of range array access"

So, How do I find out which of my literally hundreds of array refences is causing this problem?

I have tried

Code:


try{

// Code here

}

catch(...){

// Breakpoint here
}

but it does not seem to get there, instead it stops in Microsoft Code as per this:

Code:

#if defined (_M_IX86)
    volatile ULONG dw[(sizeof(CONTEXT) + sizeof(EXCEPTION_RECORD))/sizeof(ULONG)];
#endif  /* defined (_M_IX86) */

#if defined (_M_IX86) || defined (_M_X64)
    if (IsProcessorFeaturePresent(PF_FASTFAIL_AVAILABLE))
#endif  /* defined (_M_IX86) || defined (_M_X64) */
        __fastfail(FailureCode);

#if defined (_M_IX86) || defined (_M_X64)

All help much appreciated!

Pan gesture problem

$
0
0
Hello,

I'm struggling with the pan gesture in a desktop application for my Surface Pro 2.

I simply want to pan (or "swipe" if you prefer) with two fingers, but it doesn't behave like I want it to. If I put two fingers on the screen and move them straight diagonally, I receive a series of client coordinates that are aligned in a vertical or horizontal direction. Only if I perform some circular motion, then it's suddenly possible to move diagonally and receive coordinates accordingly.

I've tried with MFC, by overriding CView::OnGesturePan. I've also tried with a sample project provided by Intel, that handles the GID_PAN message in WndProc to move a rectangle around, but with the very same result. The project can be downloaded from http://software.intel.com/sites/defa...fordesktop.zip, so you can quickly reproduce the behaviour if you have a touch screen.

Code:

void GestureHandler::handlePan(HWND hWnd, GESTUREINFO gi)
{
        if (gi.dwFlags & GF_BEGIN)
        {
                m_first.x = gi.ptsLocation.x;
                m_first.y = gi.ptsLocation.y;
        }
        else
        {
                int x = gi.ptsLocation.x - m_first.x;
                int y = gi.ptsLocation.y - m_first.y;

                // ...

                m_first.x = gi.ptsLocation.x;
                m_first.y = gi.ptsLocation.y;
        }
}

I first thought it had to do with the points being too close to each other. I mean, if two points lies only one pixel apart, it can only result in eight different directions. But if I modify the code to only update "m_first" when the distance between the points are greater than some minimim distance, the points still keep being projected to a horizontal or vertical line relative to the first starting point.

Can someone be kind to explain this behaviour, and/or how to work around it?

/ Johan

Trying to throttle binary file download via WinHTTP gives unexpected results

$
0
0
Hi everyone:

My Windows service may download a binary update in the background using WinHTTP APIs. I'm using code similar to the one from the bottom of this MSDN page. For ease of access I'll copy if below:

Code:

DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
BOOL  bResults = FALSE;
HINTERNET  hSession = NULL,
          hConnect = NULL,
          hRequest = NULL;

// Use WinHttpOpen to obtain a session handle.
hSession = WinHttpOpen( L"WinHTTP Example/1.0", 
                        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
                        WINHTTP_NO_PROXY_NAME,
                        WINHTTP_NO_PROXY_BYPASS, 0);

// Specify an HTTP server.
if (hSession)
    hConnect = WinHttpConnect( hSession, L"www.microsoft.com",
                              INTERNET_DEFAULT_HTTPS_PORT, 0);

// Create an HTTP request handle.
if (hConnect)
    hRequest = WinHttpOpenRequest( hConnect, L"GET", NULL,
                                  NULL, WINHTTP_NO_REFERER,
                                  WINHTTP_DEFAULT_ACCEPT_TYPES,
                                  WINHTTP_FLAG_SECURE);

// Send a request.
if (hRequest)
    bResults = WinHttpSendRequest( hRequest,
                                  WINHTTP_NO_ADDITIONAL_HEADERS,
                                  0, WINHTTP_NO_REQUEST_DATA, 0,
                                  0, 0);


// End the request.
if (bResults)
    bResults = WinHttpReceiveResponse( hRequest, NULL);

// Keep checking for data until there is nothing left.
if (bResults)
{
    do
    {
        // Check for available data.
        dwSize = 0;
        if (!WinHttpQueryDataAvailable( hRequest, &dwSize))
        {
            printf( "Error %u in WinHttpQueryDataAvailable.\n",
                    GetLastError());
            break;
        }

        // No more available data.
        if (!dwSize)
            break;

        // Allocate space for the buffer.
        pszOutBuffer = new char[dwSize+1];
        if (!pszOutBuffer)
        {
            printf("Out of memory\n");
            break;
        }

        // Read the Data.
        ZeroMemory(pszOutBuffer, dwSize+1);

        if (!WinHttpReadData( hRequest, (LPVOID)pszOutBuffer,
                              dwSize, &dwDownloaded))
        {                                 
            printf( "Error %u in WinHttpReadData.\n", GetLastError());
        }
        else
        {
            printf("%s", pszOutBuffer);
        }

        // Free the memory allocated to the buffer.
        delete [] pszOutBuffer;

        // This condition should never be reached since WinHttpQueryDataAvailable
        // reported that there are bits to read.
        if (!dwDownloaded)
            break;

    } while (dwSize > 0);
}
else
{
    // Report any errors.
    printf( "Error %d has occurred.\n", GetLastError() );
}

// Close any open handles.
if (hRequest) WinHttpCloseHandle(hRequest);
if (hConnect) WinHttpCloseHandle(hConnect);
if (hSession) WinHttpCloseHandle(hSession);

The issue I'm experiencing is that while downloading, the code above "hogs" most of the bandwidth available on the client computer. My goal is to make it "throttle" itself on a configurable "bps" level, say at 50 kbps and not use any more bandwidth.

Someone suggested measuring my current download speed (in bps) and depending on the value make the thread "sleep" before calling WinHttpReadData again.

So the formula I'd use to calculate BPS is this:
Quote:

BPS = (BytesDownloaded * 1000 * 8) / TimePassedInMilliseconds;
then to convert to Mbps:
Quote:

Mbps = BPS / (1024 * 1024);
and the waiting/sleep would be done as such:
Code:

DWORD DesiredBitsPerSec = 50 * 1000;        //for 50 kbps

if(fBps > DesiredBitsPerSec)
{
        DWORD dwW = (DWORD)((fBps - DesiredBitsPerSec) * 1000) / DesiredBitsPerSec;
        if(dwW > 0)
                ::Sleep(dwW);                        //Sleep to throttle the download speed to the one we need
}

So I implemented it into the code above but it didn't work -- the Sleep API would produce very strange delays. So I decided to add a little bit more tracking code to actually be able to see what BPS values I'm getting.

I created a small test project that is attached to this post to illustrate the issue. (It's hard to explain without running an example.)

For a test I began downloading a large binary file (Windows 10 MSI, off Microsoft's server) and at the same time had the Task Manager open on a Performance tab that was showing me the current network throughput. I made a screenshot:

Name:  bps_test.jpg
Views: 69
Size:  54.1 KB

But as you can see, the reading on the test program and the actual network BPS values differ greatly.

The question is why? Can someone take a look at my code. I'm obviously missing something.

PS. While running multiple, repeatable tests, I made sure that nothing else on my system was using the network bandwidth on a constant basis.
Attached Images
 
Attached Files

Structures function - can someone complete this code

$
0
0
Ok so i got this assignment to complete but i need help ive started the login function but it does not run can some help mi out to see where i'm goin wrong before start the other functions.

Authentication:
Users are categorized as “Worker” or “Customer”: “Worker” can perform all
functionalities in the program. “Customer” can ONLY perform functionalities 4, 5, 6 and
7. All users are allowed three (3) attempts to enter the correct login credentials.
The CastleAmusement Tickets v1.0 software should be able to perform the following

functionalities:
1. Login: when this activity is performed, the user enters their user-id; the program
searches the “login.bat” or “login.txt” file for that user-id. If the user-id is not found in the login file the program informs the user that he/she is not a registered user and
then asks if he/she would like to register with the application. If the user chooses to
register with the application, initiate the Registration functionality (see functionality

2). Otherwise, if the user-id is found ask the user to enter their password and then
compare it with a copy of the password from the “login.*” file. If the credentials
match the program displays the program menu; other wise, advise the user that their
credentials are incorrect and ask the user is he/she wish to exit the program.

Register: when this activity is performed, the program accepts the following
customer date: full name, date of birth, age [calculated using date of birth], email
address, contact number, password, and date registered. The program should generate
a sequential user-id. Save all data (except the password) to a file called
“customer.dat”. The following data is saved to the login file (“login.dat” “login.txt”):
user-id, password, and category. The program randomly assigns a category [Worker,
Customer] to the user and informs the User of the category he/she is assigned. After the user registers successfully offer the login screen (see functionality 1).

3. Add Movie: when this activity is performed, the program accepts the following movie
data from a Worker: movie code, title, PG rating [13, 16, MA], duration in minutes,
director of the movie, type of movie [action, comedy, romance], status [active,
inactive]. Only ACTIVE movies can be scheduled for showing. The Worker uses this
activity to add a new movie to the “movies.dat” file. This file will have data
pertaining to all movies shown/showing at the movie theatre.

4. Update Movie: when this activity is performed, the program accepts the movie code
from the Worker and changes the corresponding movie status in the “movies.dat”
file.

5. Movie Schedule: when this activity is performed the program generate a daily movie
schedule from the “movies.dat” file based on ACTIVE movies. All movies are
schedule 3 hours apart. Movies are shown from 11:00A.M. to MIDNIGHT every day.
The following data is stored in a file called “movieschedule – dd-mm-yyyy.dat”:
movie code, title, PG rating [13, 16, MA], duration in minutes, director of the movie,
type of movie [action, comedy, romance], and show time and price of movie ticket.
Only one (1) movie can be scheduled in a cinema at a time.

6. Buy Ticket: when this activity is performed the program displays a copy of the movie
schedule for that day. The Customer enters the movie code and the program searches
the “movieschedule – dd-mm-yyyy.dat” file using the movie code and displays the
movie title, duration, PG rating, show date, show time and price of the ticket. The
programs then asks the user to enter payment for the ticket if he/she is sure they want
to buy that ticket. Payment must be greater than or equal to the cost of the ticket.
Once payment is validated the program prints receipt and automatically initiates the
Generate Movie Ticket functionality.

7. Generate Movie Ticket: when this activity is initiated, ticket details such as: movie
title, date of movie, show time, PG rating, and price is displayed for the customer to
view on the screen and then added to a file called “tickets.dat”.

Notes
• On STARTUP the program should ONLY display the login screen. See
functionality 1.
• The Worker can perform all functionalities. While the Customer menu can ONLY
perform 1, 2, 6, and 7.
• The theatre can only seat 100 persons. Therefore the number of tickets sold
CANNOT exceed the number of seats in the cinema. See functionality 6.
• A customer can ONLY purchase 2 tickets at a time. See functionality 6.


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>


typedef struct UserLogin
{
char userId[10];
}LOGIN;

void LOGIN()
{
char passwrd[10];
int p = 0;
char uoid[] = "ndrew";
char opasswrd[] = "program";
int chances = 3;


while (chances)
{
printf("Enter User ID:\n");
scanf_s("%s", &userId);
printf("\n");
printf("Enter Your Password:\n");
scanf_s("%s", &passwrd);

if (strcmp(uoid, userId) == 0 && strcmp(passwrd, opasswrd) == 0)
{
p = 1;
break;
}
else
{
printf("Invalid User Id And Password\n");
chances--;
}
}

if (p==1)
{
printf("Correct User Id And Password\n");
}
else
{
printf("You have no more chances...");
}
}

Where does my Application need redesigning and Speeding Up?

$
0
0
Firstly, I am using Visual Express 2013

I have a project (converted from VB6 and VC++ 6.0) that is very time intensive - it may run for hours or even weeks looking for a solution.

Currently, it structures a solution in vb.net and then passes it to native code in vc++ for evaluation. I find that it is now running at half the speed it used to run before conversion.

This suggests that it is spending a lot of time in vb.net (since the native code in vc++ is essentially the same as it always was)

Clearly, I need to know how much time it spends in every single function or subroutine (of which there are hundreds) in BOTH vb.net and vc++. Then I may well convert some of the vb.net routines into vc++ native code. Ultimately, I suspect that I will just use vb.net for all of the endless boring, non time critical stuff so that once it starts actively running it uses only vc++ native code ...

Because I am running2013 Express there is no Analyze Menu. So, what is the best way to do this (ideally, I wish to avoid upgrading Visual Studio)?

Are there any good 3rd party applications that can do this? All suggestions much appreciated ...

Read particular record in a table quickly using VC++ from MYSQL

$
0
0
Hi,

How can i read particular record in a table quickly via VC++ from MYSQL?
I have a table like
Code:

Database name: test & Table name : Profilemaster
+-----+--------+
| PID | PNAME  |
+-----+--------+
|  1 | APPLE1  |
|  2 | APPLE2  |
|  3 | APPLE3  |
|  4 | APPLE4  |
|  5 | APPLE5  |
+-----+--------+

My code is here, I was read all profilename from MYSQL database and load it to a combobox.
How can i read a particular record and store it to combobox?
Code:

void MainScreen::OnreadProfileName()
{
// TODO: Add your control notification handler code here
CDatabase database;
CString SqlString;
CString sDsn;
CString pname;

sDsn.Format("Driver={MySQL ODBC 5.2 ANSI Driver};Server=localhost;Database=test;User=root;Password=client;Option=4;");
TRY
{
// Open the database
database.Open(NULL,false,false,sDsn);
CRecordset recset( &database );
SqlString = "SELECT PNAME FROM PROFILEMASTER";
recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);

while( !recset.IsEOF() )
{
recset.GetFieldValue("PNAME",pname);
m_proname.InsertString(0,pname); //ComboBox - m_proname
recset.MoveNext();
}
database.Close();
}
CATCH(CDBException, e)
{
// If a database exception occured, show error msg
AfxMessageBox("Database error: "+e->m_strError);
}
END_CATCH;
}

How can i execute this query and get the following result
SqlString = "SELECT PNAME FROM PROFILEMASTER WHERE PID =1;";

Code:

+-----+--------+
| PID | PNAME  |
+-----+--------+
|  1 | APPLE1  |
+-----+--------+

[RESOLVED] Read particular record in a table quickly using VC++ from MYSQL

$
0
0
Hi,

How can i read particular record in a table quickly via VC++ from MYSQL?
I have a table like
Code:

Database name: test & Table name : Profilemaster
+-----+--------+
| PID | PNAME  |
+-----+--------+
|  1 | APPLE1  |
|  2 | APPLE2  |
|  3 | APPLE3  |
|  4 | APPLE4  |
|  5 | APPLE5  |
+-----+--------+

My code is here, I was read all profilename from MYSQL database and load it to a combobox.
How can i read a particular record and store it to combobox?
Code:

void MainScreen::OnreadProfileName()
{
// TODO: Add your control notification handler code here
CDatabase database;
CString SqlString;
CString sDsn;
CString pname;

sDsn.Format("Driver={MySQL ODBC 5.2 ANSI Driver};Server=localhost;Database=test;User=root;Password=client;Option=4;");
TRY
{
// Open the database
database.Open(NULL,false,false,sDsn);
CRecordset recset( &database );
SqlString = "SELECT PNAME FROM PROFILEMASTER";
recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);

while( !recset.IsEOF() )
{
recset.GetFieldValue("PNAME",pname);
m_proname.InsertString(0,pname); //ComboBox - m_proname
recset.MoveNext();
}
database.Close();
}
CATCH(CDBException, e)
{
// If a database exception occured, show error msg
AfxMessageBox("Database error: "+e->m_strError);
}
END_CATCH;
}

How can i execute this query and get the following result
SqlString = "SELECT PNAME FROM PROFILEMASTER WHERE PID =1;";

Code:

+-----+--------+
| PID | PNAME  |
+-----+--------+
|  1 | APPLE1  |
+-----+--------+

Reduce the Query Execution Time

$
0
0
Hi,

My table:
Code:

Database name: test & Table name : Profilemaster
+-----+--------+
| PID | PNAME  |
+-----+--------+
|  1 | APPLE1  |
|  2 | APPLE2  |
|  3 | APPLE3  |
|  4 | APPLE4  |
|  5 | APPLE5  |
|  6 | APPLE6  |
|  7 | APPLE7  |
|  8 | APPLE8  |
|  9 | APPLE9  |
|  10| APPLE10 |
+-----+--------+

I like to read the table and get the all PNAME into the combo box.

Using the below code i can read the table, but while loop takes 2 seconds to read 10 records in the Profilemaster table.
How can i reduce the reading time?

My Code is
[code]void MainScreen::OnreadProfileName()
{
CDatabase database;
CString SqlString;
CString sDsn;
CString pname;

sDsn.Format("Driver={MySQL ODBC 5.2 ANSI Driver};Server=localhost;Database=test;User=root;Password=client;Option=4;");
TRY
{
// Open the database
database.Open(NULL,false,false,sDsn);
CRecordset recset( &database );
SqlString = "SELECT PNAME FROM PROFILEMASTER";
recset.Open(CRecordset::forwardOnly,SqlString,CRecordset::readOnly);

LARGE_INTEGER t1, t2;
LARGE_INTEGER freq;
LONGLONG ms;
if( QueryPerformanceFrequency( &freq ) == 0 )
{
printf("Your machine not support high resolution performance counter\n");
return;
}

QueryPerformanceCounter( &t1 );

while( !recset.IsEOF() )
{
recset.GetFieldValue("PNAME",pname);
//m_proname.InsertString(0,pname); //ComboBox - m_proname
recset.MoveNext();
}
QueryPerformanceCounter( &t2 );

ms = (t2.QuadPart - t1.QuadPart) / (freq.QuadPart / 1000);
temp.Format("%d",ms);
::AfxMessageBox(temp);
database.Close();
}
CATCH(CDBException, e)
{
// If a database exception occured, show error msg
AfxMessageBox("Database error: "+e->m_strError);
}
END_CATCH;
}[code]

Is any other way to reduce the query execution time?

crypt a file [algorithm]

$
0
0
Hello, I am trying to make a basic crypting program, you simply input a file and it's crypted using ECIES.

So I use cryptopp, ( see the function : http://www.cryptopp.com/wiki/Ellipti...ryption_Scheme ).

So I thought I just needed to open the files and crypt the content like that :

Code:

file = "lorem.txt"
                        std::ifstream if1s(file);
                        std::string content((std::istreambuf_iterator<char>(if1s)), std::istreambuf_iterator<char>());
                        if1s.close();
                        ofstream myfile1;
                        myfile1.open(file);
                        myfile1 << encrypt(content);
                        myfile1.close();

encrypt is a custom made function to make encryption simplier here is the header :
Code:

string encrypt(string message);
This works pretty well on text files but when I try to crypt a 1 mb image, the output is 0.5 kb which obviously can't be right, so I wonder if there is some specific way to crypt some files.

Thanks in advance :)

read after eof

$
0
0
Hello, I'm trying to read a file which is 51563 char long ( a jpeg pic )

Name:  this-space-picture-changes-our-understanding-of-how-black-holes-form.jpg
Views: 68
Size:  26.9 KB

but whenever I open it :

Code:

std::ifstream ifs(file);
                        std::string pub((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
                        cout << pub;

I only get like 500 chars, so I tryed a lot of different funcs until I finally realized that they reached the end of file "early" well it thinks that one of the chars in it is an end of file and it's located at the start. So I really don't know what to do with it because every func doesn't see the rest of the file at all.

Any ideas ? ^^'
Attached Images
 

unusual event

$
0
0
Code:

#include <iostream>
using namespace std;
int main()
{
    cout << "Hi!" << endl;
    return 0;
}

I am back at my c++ programming, my visual studio is 2012 with service pack 4. I made a console win32 c++ program. built it and i selected "debug -> start without debugging". It opened cmd window... When I check the corner X to close it, "windows command processor" pops up with "close the program" selected. why?. could be related to windows explorer?. I have installed Microsoft install shield with limited features.

Chain Hashing

$
0
0
Hello. I am fairly new to C++. I am writing a program using chain hashing. My program begins to compile, but then errors out. I cannot seem to figure out where it is going wrong. Here is the table2.template file that I am writing.

Code:

#include <cassert>
#include <cstdlib>
#include <iostream>

namespace main_savitch_12B
{
    template <class RecordType>
    const std::size_t table<RecordType>::TABLE_SIZE;

        //CONSTRCUTORS AND DESTRUCTOR
        template <class RecordType>
        table<RecordType>::table( )
        {
            std::size_t index;
                total_records = 0;
                for (index = 0; index < TABLE_SIZE; index++)
                {
                        data[index] = NULL;
                }
        }

        template <class RecordType>
        table<RecordType>::table(const table& source)
        {
                total_records = source.total_records;

                main_savitch_6B::node<RecordType> *tail_ptr;
                std::size_t index;
                for (index = 0; index < TABLE_SIZE; index++)
                {
                        list_copy(source.data[index], data[index], tail_ptr);
                        tail_ptr = NULL;
                }               
        }

        template <class RecordType>
        table<RecordType>::~table()
        {
                std::size_t i;
                for (i = 0; i < TABLE_SIZE; ++i)
                {
                        list_clear(data[i]);
                }

                        total_records = 0;
        }

        //MODIFICATION MEMBER FUNCTIONS
        template <class RecordType>
        void table<RecordType>::insert(const RecordType& entry)
        {       
                assert(entry.key >= 0);
                main_savitch_6B::node<RecordType> *cursor;
               
                std::size_t hash_value = hash(entry.key);
                cursor = data[hash_value];

                if (cursor == NULL)
                {
                        cursor = new main_savitch_6B::node<RecordType>;
                        cursor->set_data(entry);
                } 

                else
                {
                        while (cursor->link() != NULL)
                        {
                                cursor = cursor->link();
                        }

                        cursor->set_data(entry);
                } 

                total_records++;
        }

        template <class RecordType>
        void table<RecordType>::remove(int key)
        {
                assert(key >= 0);
                main_savitch_6B::node<RecordType> *cursor;
                main_savitch_6B::node<RecordType> *precursor;
                std::size_t hash_value = hash(key);
                cursor = data[hash_value];
                precursor = 0;
               
                if(cursor == NULL)
                        return;

                else
                {
                        if (cursor->link() == NULL)
                        {
                                list_head_remove(cursor);
                        }

                        else
                        {
                                while (cursor->data().key != key)
                                {
                                        precursor = cursor;
                                        cursor = cursor->link();
                                }

                                if(cursor->link() == NULL)
                                {
                                        cursor = NULL;
                                }

                                else
                                {
                                        list_remove(precursor);
                                }       
                        }
                }
               
                total_records--;
        }

        template <class RecordType>
        void table<RecordType>::operator =(const table& source)
        {
                if( this != &source)
                {
                        data = source.data;
                        total_records = source.total_records;
                }

                return *this;
        }

        //CONSTANT MEMBER FUNCTIONS
        template <class RecordType>
        void table<RecordType>::find(int key, bool& found, RecordType& result) const
        {
                assert(key >= 0);
                main_savitch_6B::node<RecordType> *cursor;
                std::size_t index;
                index = hash(key);
               
                cursor = data[index];
               
                while ( cursor->link() != NULL && cursor->data().key  != key)
                {
                        std::cout<<cursor->data().data<<std::endl;
                        cursor = cursor->link();
                        if( cursor->data().key == key)
                        {
                                found = true;
                                result = cursor->data();
                        } 
                }

                found = false;
        }

        template <class RecordType>
        bool table<RecordType>::is_present(int key) const
        {
                assert(key >= 0);
                bool found;
                main_savitch_6B::node<RecordType> *cursor;
                std::size_t index;
                index = hash(key);
               
                cursor = data[index];
               
                while (cursor->link() != NULL)
                {
                        if (cursor->data().key == key)
                                return true;
                        cursor = cursor->link();
                }

                return false;
        }

        //HELPER MEMBER FUNCTION
    template <class RecordType>
    inline std::size_t table<RecordType>::hash(int key) const
    {
        return (key % TABLE_SIZE);
    }
}


Here is the header file.

Code:

#ifndef TABLE2_H
#define TABLE2_H
#include <cstdlib>
#include "node2.h"

namespace main_savitch_12B
{
        template <class RecordType>
        class table
        {
        public:
                // MEMBER CONSTANT
                static const std::size_t TABLE_SIZE = 811;
                // CONSTRUCTORS AND DESTRUCTOR
                table();
                table(const table& source);
                ~table();
                // MODIFICATION MEMBER FUNCTIONS
                void insert(const RecordType& entry);
                void remove(int key);
                void operator =(const table& source);
                // CONSTANT MEMBER FUNCTIONS
                void find(int key, bool& found, RecordType& result) const;
                bool is_present(int key) const;
                std::size_t size() const { return total_records; }
        private:
                main_savitch_6B::node<RecordType> *data[TABLE_SIZE];
                std::size_t total_records;
                // HELPER MEMBER FUNCTION
                std::size_t hash(int key) const;
        };
}

#include "table2.template"

#endif


Here is the program used to test my code.

Code:

#include <iostream>
#include <fstream>
#include <string>
#include "table2.h"

using namespace main_savitch_12B;
using namespace std;

struct TableRecord
{
        int key;
        double data;
};
const int MAX_KEY = 5000;
const int TABLE_SIZE = 811;

int main(int argc, char *argv[])
{
        cout << "*************************************";
        cout << "\nCSC-161 Homework Eleven Solution\n";
        cout << "*************************************";

        table<TableRecord> testTable;
        TableRecord testRecord;

        for (int index = 0; index < 100; index++)
        {

                testRecord.data = (double)index * 50;
                testRecord.key = index * 50;
                testTable.insert(testRecord);
        }

        testRecord.data = 99.0;
        testRecord.key = 300;
        testTable.insert(testRecord);

       
       
        testRecord.data = 99.0;
        testRecord.key = TABLE_SIZE;
        testTable.insert(testRecord);
        testRecord.data = 99.0;
        testRecord.key = TABLE_SIZE * 2;
        testTable.insert(testRecord);
        testRecord.data = 99.0;
        testRecord.key = TABLE_SIZE * 10;
        testTable.insert(testRecord);



        cout << "\nAdded " << testTable.size() << " records to the test table" << endl;
        cout << "*************************************";
       
        testTable.remove(100);
        testTable.remove(150);
        testTable.remove(1500);
        testTable.remove(250);
        testTable.remove(250);
        testTable.remove(3750);
        testTable.remove(4900);
        testTable.remove(TABLE_SIZE * 2);
        testTable.remove(TABLE_SIZE);
       
        cout << "\nAfter removals there are " << testTable.size() << " records in the test table" << endl;
        cout << "*************************************";
       
        cout << "\nTry some searches for key values\n";
        bool found = false;
        for (int index = 0; index < MAX_KEY; index = index + 150)
        {
                testTable.find(index, found, testRecord);
                if (found)
                        cout << "Found record with key value " << index << ", data = " << testRecord.data << endl;
                else
                        cout << "Did not find record with key value " << index << endl;
        }
       
        if (testTable.is_present(TABLE_SIZE * 10))
                cout << "\nSuccessfully found record with key equal to " << TABLE_SIZE * 10 << endl;
        else
                cout << "\n?? Failed to find record with key equal to " << TABLE_SIZE * 10 << endl;



        cout << "*************************************" << endl;
        cout << "End of Homework Eleven Solution" << endl;
        cout << "*************************************" << endl;
        system("Pause");
}


There is also a node header and template file that i did not include. The last line in the test file that processes is line 69 "cout << "\nTry some searches for key values\n";" Any help on this issue would be greatly appreciated! Thanks :)

Help me with strings pls

$
0
0
Hi I'm new to strings. I want to know how to insert a string right in the middle of another string.Is it possible to do
that? for example my first random word is 12345678 and the 2nd random word is jimmy I would have to write
this in my code uno.insert(4,dos); for jimmy to be printed in the middle of the first string,but what if my 1st random word is has more than 8 characters what would I do in that case? thanks

Code:

cout << "type random word" << endl;
getline (cin , uno);
//greatavenue
cout <<"enter random word#2"<<endl;
getline (cin , dos);
//_coconut_

uno.insert(5,dos);
       
cout<<uno<<endl;
//great_coconut_avenue

c++ need help with file processing within a switch !

$
0
0
Hello everyone. The error ive been getting with this code is after i go to the check out option, enter the data then click (ctrl + z). Then program glitches back and forth from the menu to the check out option continuously and im not entirely sure why.

Heres my code:


Code:

#include <iostream>
#include <windows.h>
#include <iomanip>
#include <fstream>

using namespace std;


           

void checkOut(){
                         
            cout << setw(10) << "Ministry of Health Hospital System\n\n\n";   
            cout << "CheckOut Form\n";
                     
            ofstream Patient("PatientRecord.txt", ios::app);
    if(!Patient){
                cerr << "Something went wrong\n";
                }
               
    string name;
    int num;
    double charges;
 
    cout << "Enter Patient Number, Name & Charges then (CTRL + Z) to exit\n";
    while(cin >> num >> name >> charges){
              Patient << num << " " << name <<  "  $" << charges << endl;
              }         
           
             
    }

int main(){
   
    char c;
      while(c!='x'){
                 
      cout << setw(10) << "Ministry of Health Hospital System\n\n\n";
      cout << setw(10) << "MENU" << endl;
     
      cout << "C - Checkout Patient\nD - Display Hospital Records\nX - Exit\n";
      cout << "option ?";
      cin >> c;   
     
          switch(tolower(c)){
                            case 'c':
                      system("cls");
    checkOut();
      Sleep(3000);
              system("cls"); 
              break;
                case 'd':
                      system("cls");
                      cout << setw(10) << "Ministry of Health Hospital System\n\n\n";   
            cout << "Hospital Records Display\n";
                     
            ifstream Patient("PatientRecord.txt", ios::in);
              if(!Patient){
                cerr << "Something went wrong\n";
                }
               
    string name;
    int num;
    double charges;
    while(Patient >> name >> num >> charges){
                  cout << num << " "<< name << " $" << charges << endl;
                  }
   
                      system("pause");
                      Sleep(3000);
              system("cls"); 
        break;
       
        case 'x':
              cout << "GoodBye !\n";
             
              break;
        default:
                cout << "Invalid input!\n";
                system("pause");
                system("cls");
               
 
                     
                  }
                  }
   
    system("pause");
    return 0;
    }

Unable to pass arguments to DLL function

$
0
0
Hi, Folks,

I have some trouble with DLL.

I created a dll with function

double square(const double * args)

and then in my application defines

typedef double (*MyFunct)(const double *args);

I use LoadLibrary and GetProcAddress to get the function address and cast it to MyFunct. Everything works fine except that when I pass a double *, for example 0x08800350, to the DLL function, the argument becomes totally something else, for example, 0x0aa00460.

I have no clue what happens to the argument value. Could someone please help me out?

Thank you so much!

CR
Viewing all 3017 articles
Browse latest View live