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

Enable white spaces when writing inputted strings to a text file

$
0
0
When I used a simple code example from my text book:

Code:

//This program writes user input to a file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ofstream outputFile;//create object for writing data to file
    string name1, name2, name3;

    //open an output file:
    outputFile.open("Friends.txt");

    //Get the names of three friends:
    cout << "Enter the names of three friends.\n";
    cout << "Friend 1: ";
    cin >> name1;
    cout << "Friend 2: ";
    cin >> name2;
    cout << "Friend 3: ";
    cin >> name3;

    //Write the names to the file:
    outputFile << name1 << endl;
    outputFile << name2 << endl;
    outputFile << name3 << endl;
    cout << "The names were saved to a file.\n";

    //Close the file:
    outputFile.close();

    system("pause");
    return 0;
}

This is how the program reacted to the white space in the string "Angry Grandpa":
Name:  WhitespaceError.jpg
Views: 57
Size:  23.4 KB

How do I fix this behavior, so that a white space is allowed (for both my friends' first and last name to be seen as one string)?
Attached Images
 

Builder and Stub Help

$
0
0
Okay i have a problem i coded this cos i wanted to test something Like a Builder and Stub and that has been one of my major nightmares these days

My question goes like this i have an application (Which is the stub), its suppose to gather information and send vis Wininet like this

Code:

**stub.cpp**

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <Wininet.h>

#pragma comment(lib, "wininet.lib")

int main()
{
    char fullname,tel,email[250];
    printf("Enter First name: \n");
    scanf("%s",&fullname); 
    printf("Enter Telephone: \n");
    scanf("%s",&tel);
    printf("Enter Email: \n");
    scanf("%s",&email);

    static TCHAR hdrs[] =
      _T("Content-Type: application/x-www-form-urlencoded");
  static TCHAR frmdata[] =
      _T("fullname=fullname&tel=telephone&Email=&email");
  static LPSTR accept[2]={"*/*", NULL};

    HINTERNET hSession = InternetOpen("MyAgent",INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
        HINTERNET hConnect = InternetConnect(hSession, _T("ServerNameHere"),INTERNET_DEFAULT_HTTP_PORT, NULL, NULL,INTERNET_SERVICE_HTTP, 0, 1);
  HINTERNET hRequest = HttpOpenRequest(hConnect, "POST",_T("FormActionHere"), NULL, NULL, accept, 0, 1);
  HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));

//Internet close For others here

    return 0;
}

Now here is the Builder which i would use to load the stub

Code:

Builder.cpp

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>

#include "resource.h"

int main()
{
    char url[50];
    printf("Enter URL: \n");
    scanf("%s",&url);

    // Extract file from Resource

    HRSRC hrsrc = FindResource(NULL, MAKEINTRESOURCE(wResId) , IDC_FILE1);
    HGLOBAL hLoaded = LoadResource( NULL,hrsrc);
    LPVOID lpLock =  LockResource( hLoaded);
    DWORD dwSize = SizeofResource(NULL, hrsrc);
    HANDLE hFile = CreateFile  (lpszOutputPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
    DWORD dwByteWritten;
    WriteFile(hFile, lpLock , dwSize , &dwByteWritten , NULL);
    CloseHandle(hFile);
    FreeResource(hLoaded);


    MessageBoxA(NULL, "Done :)", "", MB_OK);


    return 0;
}

Now here goes my question, I want the file to load the other file in resource, the localhost part works fine, but i want it this time to use the domain which is online other than the localhost. This has been givving me issues and i need help to fix it. kindly help someone.

PS: I am typing from a mobile as i didnt use a compiler :)

Problem in templates in C++

$
0
0
Hello guys.
Please have a look at the code below:


Code:

#include <iostream.h>
using namespace std;

template<class T> class S {
                T val;
public:
        S<T>(T v) { val = v; }
};

//----------------------------

template <class T> ostream& operator<<(ostream& os, T& to) {
        os << to;
        return os;
}

//------------------------------------

template <class T> void show(T t) {
        cout << t;
}

//---------------------------

int main()
{
        S<int> s1(5);
        show(s1);
       
        return 0;
}

When I run it hitting F5 in Visual Studio 2012, I get run time errors. I don't know what the problem is. Can you help me please?

Access database with MFC, vc++ 6.0

$
0
0
Hi all,

I just join Codeguru. In the hope that It is Last option to try.

I am very new in VC++ 6.0. Before few day my head assign me task of implementing a printHeader module. Which I have to add into already implemented project in vc++ 6.0 before 6 or 7 years.
as I read MSDN,Ask question on many forum able to implement some what like adding data to access database.
My task is:

1] Older Project is a software which take a readings and generate Report according to it. (I do not have have to deal with it).
2] But at the time of print first printHeader is write on document then Reading are write on document.
3]Report is generated as per the companies to whom the required. Header contain Some entry from which some are constant and some have to change.
i)Company Name ii)Address iii)Order number iv)ModelNumber v)Tel no vi)Logo (logo of company- picture control(bitmap))
4]My task is to implement
i)Configure PrintHeader.Means if new company came then All above entries are store in access database.
ii)On other Dialogbox Only name of company shown in Listbox or Dropdown box. When user select particular company name then automatically entry with that company name retrieve and write into the document in Header at fixed location.

*Old Project does not used databased in it.
*Project in vc++ 6.0
*access database

Please Help. if some one implement it then I am very thank full to him/her.
Attached Images
 

How to create a Excel File(.XLSX) And(.XSL) through code in MFC

$
0
0
hiii can anybody help me here..
i am trying to create an excel file through code.but i am not able to..
i tried using CStdioFile class but its not working..
here is some part of my code..the one which fails,

try
{
Cstring Strname = path + s_excel; // FINDS .XSL FILE
lpdisp= books.open(strname,covOptional,covOptional,covOptional,covOptional,covOptional
covOptional,covOptional,covOptional,covOptional,covOptional);
assert(lpdisp);
}
catch(COleDispathException *e)
{

Cstring Strname = path + X_excel; // FIND .XLSX FILE
lpdisp= books.open(strname,covOptional,covOptional,covOptional,covOptional,covOptional
covOptional,covOptional,covOptional,covOptional,covOptional);
assert(lpdisp);


}

please help if anyone can..

Defining operators for vectors of templates

$
0
0
I'm reading Programming Principles and Practice Using C++ first edition first printing book. This book is really hard for beginners but I have studied it until chapter 19 and should finish it!

I have a problem with a drill in chapter 19. Please look at it in the link below.
http://uploads.im/S0mun.png

I have written the following code for questions number 1 through 13 of that drill but I have problems with the question number 14 of it.
There is no guide/sample on/of it in the chapter! So I don't know how to solve it. :(

Code:

#include <iostream>
using namespace std;

template <class T> class S {
public:
        T val;
        S(T v) { val = v; }
        T& operator[](int);
        const T& operator[](int) const;
};

//-----------------------------------------

template<class T> T& S<T>::operator[](int n) { 
        return val[n];
}

//---------------------------------------------------

template<class T> const T& S<T>::operator[](int n) const { 
        return val[n];
}

//--------------------------------------------------------

template <class T> istream& operator>>(istream& i_s, S<T>& v_i) {
        return i_s >> v_i.val;
}

//--------------------------------------------------

template <class T> ostream& operator<<(ostream& o_s, const S<T>& v_o) {
        return o_s << v_o.val;
}

//---------------------------------------

template <class T> ostream& operator<<(ostream& o_s, const S<vector<T>>& v_o) {
        return o_s << v_o.val;
}

//---------------------------------------

template<class T> void read_val(T& v) {
        cin >> v;
}

//-------------------------------

template<class T> void write_val(const T& v) {
        cout << v << '\n';
}

//-----------------------------------------

template<class T> void write_val(const vector <T>& v) {
        for(int i=0; i<v.size(); i++)
                cout << v[i] << ' ';
        cout << endl;
}

//------------------------------------

int main() 
{
        vector<int> vs;
        for(int i=0; i<5; i++)
                vs.push_back(i*i);

        S<int> s1(5);
        S<char> s2('c');
        S<double> s3(5.25);
        S<string> s4("Template");
        S<vector<int>> s5(vs);
   
        write_val(s1);
        write_val(s5);
       
        return 0;

}

The program runs successfully until write_val(s1); but facing write_val(s5); I get this error:

Error 1 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'const Vector<T>' (or there is no acceptable conversion) c:\users\me\documents\visual studio 2012\projects\test1\test1\test1.cpp 39

Please don't use friend feature. I haven't learnt it so far and likely I will learn it the next chapters of the book. :)
Thanks in advance.

LoadImage bitmap runtime

$
0
0
I want to display Logo on my document like other data which I retrieve from database are store into variable and then those are passes to print on document. I am storing path of related bitmap in database and it is also retrieve into variable I know following:


hbit = (HBITMAP) LoadImage(AfxGetInstanceHandle(),
// MAKEINTRESOURCE(IDB_BITMAP4),
MAKEINTRESOURCE(IDB_BITMAPNAME),
IMAGE_BITMAP,
0,
0,
LR_CREATEDIBSECTION); SRCCOPY);



IDB_BITMAPNAME is a BITMAP which File Name Property set to the logo's path.

This is a static way to do means I already set FileName Property of BITMAP. I want to set it at runtime. please help


I tried as follows but not work,

hbit = (HBITMAP) LoadImage(NULL,
// MAKEINTRESOURCE(IDB_BITMAP4),
sLogopath,
IMAGE_BITMAP,
0,
0,
LR_LOADFROMFILE);

sLogoPath is CString type variable which contain C:\Users\Administrator\Desktop\cg_logoa.bmp path of bitmap

I also tried for dilectly mention path instead of variable "C:\\Users\\Administrator\\Desktop\\cg_logoa.bmp"

Also tried for this

L"C:\\Users\\Administrator\\Desktop\\cg_logoa.bmp" but it gives following error

error C2664: 'LoadImageA' : cannot convert parameter 2 from 'unsigned short [44]' to 'const char *'

select item from listbox and diplay into editbox in mfc vc++

$
0
0
I have a list control on my dialog-box which contain list of names. when one particular name is selcted then display it in editbox control. How to do this in mfc? better if provide one simple code example.

How to link a static library struct to a user app ?

$
0
0
Using a struct object can be quite useful to combine several different data types into a single package. I have tried to do this utilizing a static library, but have run into problems. The main problem is to get the calling app to access the library struct. I have attached a small demo to illustrate the problem. Any help greatly appreciated. Thanks.
Attached Files

[RESOLVED] How can I free up Codeguru server space to delete old uploads?

$
0
0
I have exceeded my server space allotment and can no longer upload demo apps. What should I do? The Manage Attachments interface is not particularly intuitive.

ComboBoxe delete list only

$
0
0
Hello

I just cannot find how to delete the list only in a drop list combobox without deleting the text in the edit control as well.

I tried to insert the saved text but there seems no command to do so.

Is it at all possible?

How to use flint library in visual studio 2013

InitiateShutdown fails for a remote computer with RPC_S_SERVER_UNAVAILABLE error

$
0
0
I'm trying to implement rebooting of a remote computer with InitiateShutdown API using the following code, but it fails with RPC_S_SERVER_UNAVAILABLE or 1722 error code:

Code:

//Process is running as administrator
LPCTSTR pServerName = L"\\\\192.168.42.105";

if(AdjustPrivilege(NULL, L"SeShutdownPrivilege", TRUE) &&
    AdjustPrivilege(pServerName, L"SeRemoteShutdownPrivilege", TRUE))
{
    int nErrorCode = ::InitiateShutdown(pServerName, NULL, 30,
                                        SHUTDOWN_INSTALL_UPDATES | SHUTDOWN_RESTART, 0);

    //Receive nErrorCode == 1722, or RPC_S_SERVER_UNAVAILABLE
}



BOOL AdjustPrivilege(LPCTSTR pStrMachine, LPCTSTR pPrivilegeName, BOOL bEnable)
{
    HANDLE hToken;
    TOKEN_PRIVILEGES tkp;
    BOOL bRes = FALSE;

    if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
        return FALSE;

    if(LookupPrivilegeValue(pStrMachine, pPrivilegeName, &tkp.Privileges[0].Luid))
    {
        tkp.PrivilegeCount = 1; 
        tkp.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : SE_PRIVILEGE_REMOVED;

        bRes = AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
        int nOSError = GetLastError();
        if(bRes)
        {
            if(nOSError != ERROR_SUCCESS)
                bRes = FALSE;
        }
    }

    CloseHandle(hToken);

    return bRes;
}

192.168.42.105 computer has file and printer sharing enabled on the network.

Note that the following shutdown command seems to work just fine to reboot the remote computer:

Code:

shutdown /r /m \\192.168.42.105 /t 30
What am I missing with my code?

pass variable value from one dialogbox to other/ one class to other class in vc++ MFC

$
0
0
hello,

I am trying to pass variable of one class to other class, i did this by calling that doalogbox using DoModal method . But it give retry,Abort,ignore type of messagebox/ Exception.
Is there any way to access variable of one class to other class.

help in exam

$
0
0
that is exam i need it's answer
1- write a program that reads 2 strings of the same length from the user and prints"same" if these strings are identical
else it prints"different"

2- find and correct the error
a- void fun(const int b[],int n)
{ for(int i=0,i<n,i++)cout<<++b[];}
void main( ){ int a[5]={2,4,3,5,6}:fun{a,5);}

b- int b[9]={0,1,2,3,4,5,6,7,8,9};
for (int i=0,i<=9.i++)b[i]=i;

3-what will the output of the following code
float x[10]={5.5,6.5,7.5,8.5,9.5,12.5,14.5,16.5,18.5,20.5}
cout <<static cast<int>(x[9/2]/2;

4- write a program that reads the mode value of the following data elements
{1,1,2,2,3,5,5,9,8,7,7,5,2,75,2,2,4,4,)

give path of logo with ~ sign in vc++ 6.0

$
0
0
I am storing logo (Bitmap) path into database. By using File upload when I browse the Logo(bitmap) and select logo it's whole path is selected. can we use ~ sign by which just name of bitmap have to store and ~ sign get remain path automatically in vc++ 6.0

How to Avoid retry,ignor,abort type error/Exception in vc++ 6.0

$
0
0
Hello,

I implement one project in vc++ 6.0, My project is working fine but it gives run time error/exception of abort,retry,ignor. How to avoid this exception ?

Sending email using SMTP

$
0
0
I am writing a C++ program for sending emails automatically. I downloaded sample code which uses SMTP for sending emails. But the program is not working. When we are calling gethostbyname("smtp.gmail.com") I get an error:WSAHOST_NOT_FOUND.

To send emails I had to log in a proxy server. I manually logged in the proxy server and then only I tried my program.

Please help me.

Passing a struct to and from a DLL

$
0
0
I have a DLL that uses a struct that is defined in a separate file, misc.h.
Code:

// misc.h
typedef struct
{
        wstring wsvarstr;
        wstring wsvarnam;
        TNT::Matrix<double> Mf;
        vector<int> vndim;
        vector<wstring> vwsdxs;
} sTensor;

The DLL header:
Code:

#include "misc.h"


extern "C"
{
        void TAIP_API StartMyLib();
        void TAIP_API DumpTensor(sTensor st);
        void TAIP_API PrintTensor(sTensor st);
        void TAIP_API SetTensor(sTensor * st);
        int TAIP_API ReadVariableMap(wchar_t * varfilepath);
        void TAIP_API DumpVariableMap();
        int TAIP_API GetTensorVariable(wstring wsvarnam, sTensor &tensor);
        void TAIP_API ListVariables();
        void TAIP_API ListVarStrings();

}

The DLL methods utilize a class, CVarStack that also uses misc.h to define the struct sTensor.

What is remarkable to me is that this works at all, but it does. Quite nicely, in fact. Without compiler warnings,
errors, or leaks.

My understanding of DLLs is that one should not (cannot ?) pass reference objects as input parameters. In addition,
C-Linkage prohibits stl input parameters such as wstring and the presumably the stl contents of the struct.

My questions are:
1 - Why does this code work on VS 2010, VS2015 (Win 7 64-bit)?
2 - Can this code be relied upon to work on other Windows machines (Win2K, Vista, Win8, Win10) ?

Thanks for your comments.

Using Slider Control in client area

$
0
0
Hi ,

I want to use Slider Control in Client Area to set some parameters.

How to do this ? I have used it in Dialog Box Only.

Thanking you ..

New_2012
Viewing all 3021 articles
Browse latest View live