Quantcast
Channel: Visual C forum
Viewing all 15302 articles
Browse latest View live

How can I insert a loop into this program

$
0
0

First thank you to all the people who replied in my previous post: SimonRev, Igor Tandetnik.

I am new to programming, so please excuse my lack of technical terms and knowledge in this subject. I wrote a program, it only took me like 4 days...hahaha. I now have to integrate a loop into the program. I am just not sure where it should go, or how to go about doing it. 

Any input, advice would be greatly appreciated. Please see my code below.


#define _CRT_SECURE_NO_WARNINGS

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

float sentry(void)
{
    float s;
    printf("Please enter the salary of your Employee:");
    scanf("%f", (&s));
    return s;

}

float raises(float s)
{
    if (s>0 && s<30000)
        return .07;
    else if (s>30000 && s <= 40000)
        return .055;
    else if (s>40000)
        return .04;
}

void print(float salary, float incr)
{
    printf("Initial salary : %.2f\n", salary);
    printf("Increase     :  %.2f %%\n", incr * 100);
    printf("Raise amount : %.2f\n", salary * incr);
    printf("New Salary :  %.2f\n", salary + (salary * incr));
}

int main(void)
{
    float salary;
    float incr;
    printf("Salaries and raises calculator\n\n");
    salary = sentry();
    incr = raises(salary);
    print(salary, incr);



    system("pause");
}


CDHTMLDialog Causes Errors on App Exit

$
0
0

I have an embedded CMFCListCtrl in report mode inside a CFormView derived class. The View also has an embedded toolbar. One of the buttons calls the CDHTMLDialog.

Everything works fine up to that point. The Dialog opens.  Here is the problem:

If I open the CDHTMLDialog and close the app: No errors.

If I first populate the CMFCListCtrl. Call the CDHTMLDialog and close the app. I First get an access violation and a break point on AfxDeactivateActCtx with the following errors:

First-chance exception at 0x78b64f64 (mfc90ud.dll) in PManager.exe: 0xC0000005: Access violation reading location 0x00000000075f3d70. First-chance exception at 0x771eb3dc in PManager.exe: 0xC015000F: The activation context being deactivated is not the most recently activated one. First-chance exception at 0x771eb3dc in PManager.exe: 0xC015000F: The activation context being deactivated is not the most recently activated one. First-chance exception at 0x771eb3dc in PManager.exe: 0xC015000F: The activation context being deactivated is not the most recently activated one. First-chance exception at 0x771eb3dc in PManager.exe: 0xC015000F: The activation context being deactivated is not the most recently activated one. Unhandled exception at 0x771eb3dc in PManager.exe: 0xC015000F: The activation context being deactivated is not the most recently activated one.

I have tried literally everything and have not found a solution.


Robert C Finnegan

Elaborated-type-specifier injects a class declaration in enclosing namespace. But the code still compiles when variable with the same name is uncommented in the code.

$
0
0

The following snippet should not compile if the declaration `int B;` in namespace X::Y, is uncommented, as I explain in the comments below. So, I believe this is a bug in VS2013 update 4. (live example).

namespace X {
    namespace Y {
        //int B;
        struct C
        {
            struct A
            {
                A() { p = nullptr; }
                struct B* p;            // `struct B` is an elaborated-type-specifier in this declaration (see
                                        // [basic.lookup.elab] C++14) and this declaration is the FIRST in its
                                        // translation unit. Thus, according to [basic.scope.pdecl]/7 bullet
                                        // point (7.2), "the identifier is declared in the smallest namespace
                                        // or block scope that constains the declaration". That is, the
                                        // declaration `struct B;` is injected by the compiler in the namespace X::Y,
                                        // and this makes the declaration (definition) of the function f correct, as
                                        // a lookup for the name B, started at the function parameter `X::Y::B&` will
                                        // find the name in the injected declaration in the namespace X::Y.
                                        //
                                        // However, if we uncomment the declaration `int B;` in X::Y, the code
                                        // should not compile, for the injected declaration `struct B;` will be
                                        // hidden by the `int B;` declaration, according to [basic.scope.hiding]/2.
            };
        };
    }
}

void f(X::Y::B& b)
{
}

int main()
{
    X::Y::C::A a;
    f(*a.p);
}


Building regular DLL based on static libs compiled with _AFXDLL

$
0
0

I am trying to build a regular DLL that depends upon a set of static libs I get from elsewhere. The static libs are compiled with _AFXDLL and _AFXEXT and /MD. (The static libs are used by a different application that uses shared MFC libs.)

I can link the dll, but when it runs it fails to find CRuntimeType information for classes in those static libs. Specifically, some source in the static libs is calling:

AFX_MODULE_STATE *afxs = AfxGetModuleState();

and looking thru the afxs->m_classList which happens to be NULL. (There should be lots of classes there.)

Currently my regular DLL is linking agains the static MFC libs.

To be clear, I do not want to export any MFC classes from my dll, the MFC classes are only used internally by the static libs I'm linking my dll against. That's why I am using a regular (not mfx extension) dll.

Do I need to link my dll with shared mfc? I have a fair amount of exported functions. I would have to add

AFX_MANAGE_STATE(AfxGetStaticModuleState( ))

to every exported function right?

Win8 Spell Checker doesn't instantiate?

$
0
0

I am implementing a Windows 8 spell checker service using the API at https://msdn.microsoft.com/en-us/library/windows/desktop/hh869748.aspx but msspellcheckinghost.exe never uses it for anything.

The host will load the DLL and call ISpellCheckProviderFactory::get_SupportedLanguages(), but then it just unloads the DLL.

Spell checking is globally enabled and apps like Skype do use built-in speller, but even though I add more locales to the DLL (in my case en-US, da-DL, kl-GL) and I ensure that I have those locales enabled and selected in Windows, none of them ever make it beyond get_SupportedLanguages().

This happens both with the sample project and with my own from-scratch project, so I can only conclude something in Windows is either configured incorrectly or buggy, but I don't know what. And it also happens on multiple machines, which leads me to think Windows' default behavior is to ignore 3rd party spellers.

Any ideas how I can proceed?

Error compiling projects

$
0
0

I am using QT together with vs2013. In any project that involves a external library to link I got the following error:

LINK : fatal error LNK1181: cannot open input file 'link.obj'

Does anybody have any idea why this occur? Any suggestions for a way to find out the reason of the problem?

thanks for the attention, any help is welcome

I look forward to an answer

Can I know the precision and scale of a decimal field using ACEDAO?

$
0
0

Using ACEDAO in VC++, I am trying to retrieve the field details of an Access database (.accdb file) table of which one field is of decimal type. I am able to get the details using the functions of

DAO::_FieldPtr field;

as follows:

fieldName = field->GetName().GetBSTR();
nType = field->GetType()   // returns DAO::dbDecimal
lSize = field->GetSize();  // returns 16
lAttr = field->GetAttributes();  // returns 0x000002H
nOrdinal = field->GetOrdinalPosition(); // returns 11
bAutoIncrement = ((lAttr & DAO::dbAutoIncrField) > 0);

DAO::PropertiesPtr props;
DAO::PropertyPtr prop;
int k, nProp;
std::wstring propName, propNames;

props = field->GetProperties();

if(props)
{
	nProp = props->GetCount();  // returns 33
        for(k = 0; k < nProp; k++)
        {
            prop = field->GetProperties()->GetItem((short) k);
	    if(prop)
	    {
		propName = prop->GetName().GetBSTR();
                propNames += propName;
                propNames += L"\n";
            }
        }

        // After exiting the loop, propNames contain 33 properties as:
	//	Value
	//	Attributes
	//	CollatingOrder
	//	Type
	//	Name
	//	OrdinalPosition
	//	Size
	//	SourceField
	//	SourceTable
	//	ValidateOnSet
	//	DataUpdatable
	//	ForeignName
	//	DefaultValue
	//	ValidationRule
	//	ValidationText
	//	Required
	//	AllowZeroLength
	//	AppendOnly
	//	Expression
	//	FieldSize
	//	OriginalValue
	//	VisibleValue
	//	GUID
	//	ColumnWidth
	//	ColumnOrder
	//	ColumnHidden
	//	Description
	//	DecimalPlaces
	//	DisplayControl
	//	TextAlign
	//	AggregateType
	//	ResultType
	//	CurrencyLCID
        //But does not have any property named "Scale" or "Precision"
}
I could not find any function for retrieving the value for precision and scale for the decimal field.

Though I am able to retrieve the field value as a decimal number and get the required information from the structure, I think it is not the right way. Because, what will happen if the data for field is not available in the table?

Is there any other method to retrieve the precision and scale of a decimal type field using ACEDAO?

Thanks.

Operating System Development

$
0
0

Hi ,

       I am in a new project of developing an operating system . Those who are interested can join https://leafos.visualstudio.com .

       Your contribution counts .

       Thank You .


Cannot compile source file with Ctrl-F7 in VS 2008

$
0
0

I have added an existing .cpp file to my project.  When I want to compileonly one file, I usually press Ctrl-F7, but that does not work on this file (it works on some other source files).  When I pull down the Build menu, the Compile option is missing, like it is when a header (*.h) file is active.

When I right-click on the source file in the Solution Explorer, the context menu shows "Compile\tCtrl+F7"; I can compile a single source file that way, but Ctrl-F7 is so much easier and faster.

I have tried resetting the keyboard shortcut, resetting the profile to the original C/C++ profile, and closing and reopening Visual Studio, but nothing corrected the issue.

It feels like VS is not recognizing that my source file is a C++ file, despite its name (something.cpp).  Why has this started happening, and how can I get the shortcut (and Build menu) to reset?

How to send a file using IOCP?

$
0
0

When using blocking sockets, all I had to do to send a file was to open the file and loop through it and send it in chunks.

But I find sending a file using overlapped sockets to be more challenging. I can think of the following approach to do it:

  1. I open the file and send the first chunk, and I keep track of the file handle and file position.
  2. Now when I get a completion packet indicating that some data has been sent, I check to see if the socket is currently in the process of sending a file, and if it is, I retrieve the file handle and file position and send the next chunk.
  3. I repeat step 2 until I reach the last chunk in the file, and then I close the file.

Is this approach correct?

Note: I don't want to use TransmitFile().


Adding folders to visual studio project template

$
0
0

I want to add the following folders to the project directory.

include 

dep/binary

dep/lib

dep/include

So I created a project template and edited the MyTemplate.vstemplate file like below

<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
  <TemplateData>
    <Name>SFML</Name>
    <Description>&lt;No description available&gt;</Description>
    <ProjectType>VC</ProjectType>
    <ProjectSubType>
    </ProjectSubType>
    <SortOrder>1000</SortOrder>
    <CreateNewFolder>true</CreateNewFolder>
    <DefaultName>SFML</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
    <LocationField>Enabled</LocationField>
    <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <Project TargetFileName="ProjectS.vcxproj" File="ProjectS.vcxproj" ReplaceParameters="true">
      <ProjectItem ReplaceParameters="false" TargetFileName="$projectname$.vcxproj.filters">ProjectS.vcxproj.filters</ProjectItem>
      <ProjectItem ReplaceParameters="false" TargetFileName="main.cpp">SRC\main.cpp</ProjectItem>
      <Folder Name="dep">
        <Folder Name="binary"></Folder>
        <Folder Name="lib"></Folder>
        <Folder Name="include"></Folder>
      </Folder>
      <Folder Name="include"></Folder>
    </Project>
  </TemplateContent>
</VSTemplate>

But when I create a new project using this template, the folders are not there. What have I done wrong?

CL.exe not found

$
0
0

Hey there,

i installed Visual Studio 2013 Ultimate on my D drive ( not my system drive), as I couldn't change it during setup.

So my path is "D:\Programme\Visual Studio 2013 Premium" to my IDE.  Anyway, when i try to import a project it errors with "Error 1 error TRK0005: Failed to locate: "CL.exe". The system cannot find the file specified."

I know that many answers are like "use the .bat in your /VC/bin folder" but none of these advices worked for me. Can be the installation on D be the cause for this?

How do i change the install path? It was locked to D: for me.

Greetings

Calling CreateFile()\DeviceIoControl() API to communicate with driver need administrator privillage in local user account?

$
0
0

 Hi,

I need to use following APIs to communicate with driver using IOCTL codes.

   CreateFile() - To get the handle
   DeviceIoControl() - To send the IOCTL code to driver and get result.

Is it possible to run these API from local user account?

Or Need any administrator privillage to run this APIs?

Please confirm..

 

In MSDN documentation of CreateFile I found the following

From MSDN


You can use the CreateFile function to open a physical disk drive or a volume, which returns a direct access storage device (DASD) handle that can be used with the DeviceIoControl function. This enables you to access the disk or volume directly, for example such disk metadata as the partition table. However, this type of access also exposes the disk drive or volume to potential data loss, because an incorrect write to a disk using this mechanism could make its contents inaccessible to the operating system. To ensure data integrity, be sure to become familiar with DeviceIoControl and how other APIs behave differently with a direct access handle as opposed to a file system handle.

The following requirements must be met for such a call to succeed:

•The caller must have administrative privileges. For more information, see Running with Special Privileges.
•The dwCreationDisposition parameter must have the OPEN_EXISTINGflag.
•When opening a volume or floppy disk, the dwShareMode parameter must have the FILE_SHARE_WRITEflag.

Thanks,
Bhash

Using CMFCListCtrl In CFormView

$
0
0

I am currently revising one of my programs that originally had the list control in a dialog. The program worked fine but now I am using views instead of dialogs.

The list control and every other aspect of the code works fine until I try and use OnNMClick and

GetItemIndexRect I am using the same method I used when it was in the dialog

LPNMITEMACTIVATE pNMItemActivate =

reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);

LVITEMINDEX lvItemIndex;

lvItemIndex.iGroup = 0;

lvItemIndex.iItem = pNMItemActivate->iItem;

CRect rect;

GetItemIndexRect(&lvItemIndex,pNMItemActivate->iSubItem,LVIR_BOUNDS,&rect);

However now GetItemIndexRect is returning false. I traced the iItem and iSubItem and they are correct when an item is clicked on yet the call fails.


Robert C Finnegan


Where is WCHAR defined?

$
0
0

I created a console app to assist in testing a short utility.  In there I wrote:

Const WCHAR dir_name[] = L”C:\\TEMP”;

The compiler says Error1             error C4430: missing type specifier - int assumed. Note: C++ does not support default-int               e:\code\delete_all_files_in_a_directory\delete_all_files_in_a_directory\delete_all_files_in_a_directory.cpp 12               Delete_All_Files_In_A_Directory

I used the defaults and the project properties shows: Use Unicode Character Set.

I used Google and Bing and the phrase:  visual studio where is WCHAR defineddoes not solicit the answer.

Here is the msdn page on WCHAR: https://msdn.microsoft.com/en-us/library/gg269344(v=exchg.10).aspx

It does not say where WCHAR is defined.

This page: https://social.msdn.microsoft.com/Forums/vstudio/en-us/750e1b3c-1b8f-4b64-9f9b-ee9bdedbfd34/char-wchar-tchar-galore?forum=vclanguage

Describes WCHAR but does not say where it is declared.

So,...,

1. What include file is needed for WCHAR?

2. Why is this so difficult to find?  (A rhetorical question.  Microsoft provides an incredible wealth of information.  But it is sometimes so incredibly difficult to find.)


~jag77 We need to know what a dragon is before we study its anatomy. (Bryan Kelly, 2010)


Using C++ to create a structure chart designer

$
0
0

I am trying to use C++ to design a structure chart program that will let you enter in names of functions into a sidebar and as you enter a name into the first slot two things will happen: another blank slot will appear below the one you are typing in and a text box (shaped to the size of the text inside) will appear in the main area allowing the structure chart to expand. Another part will be to put some kind of tab on the text entry slots so that you can add different lines to any other function boxes including main() and allows you to put the variable names that are being passed in and out of functions on or near the lines that go between them all. It will basically be just what you would expect out of a structure chart, just automated and neat.

Let me know if there is any advice or help you can give me as I start this program. 

Thanks in advance!

Microsoft Cryptography Next Generation CNG Windows 7 machine

$
0
0

Hi Guys,

I developed a sample encryption application using Microsoft Cryptography Next Generation (CNG) in C++ using bcrypt.h header file. I tried using AES 128bit CFB mode. The cipher text generated by my application is different from cipher text generated by OpenSSL CFB API. The plain text, key and IV are all same between CNG and OpenSSL.

Is there any extra property to be set in CNG to produce exact output as per OpenSSL? 

I followed the example given below https://msdn.microsoft.com/en-us/library/aa376234(v=vs.85).aspx and just changed CBC to CFB.

Will the example support CFB mode?

[MFC] Edit control CEdit has some strange behavior when multiline

$
0
0

In a MFC application: 1. Create a MFC dialog. 2. In Visual Studio resource editor, drag an Edit Control to above dialog. 3. Change 2 properties below: - Auto HScroll = False. - Multiline = TRUE 4. Change height of Edit Control so that it can contain 2 line of text. 5. Run application. 6. Input "-WWWWW" into Edit Control When input a character that width of text is greater than width of Edit Control, normaly, Edit Control is break down new line. But when input "-WWWWW" and continue input "W" -> Edit Control create 2 the same line "WWWWW".

Please help me to fix this issue.

Thanks & Regards

How Tall Is This Column of Rich Text?

$
0
0

Hello Folks:

   Resolved.  I just had to pass in the column width in twips.

      Thanks

      Larry



No warning when assigning to an unsigned char from unsigned int

$
0
0

Is this an error in VC++, or am I missing something?  The following code should give two warnings for assigning to a smaller type, but only gives one: (compiled as 32 bit)

unsignedchar c;

unsignedint i = 24;// 32 bit unsigned integer

unsignedlong L = 25;// Also a 32 bit unsigned integer

c = L; // Warning C4244

c = i; // no warning

This happens in Visual Studios 2005, 2010, 2012, 2013 and 2015, at least.

Viewing all 15302 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>