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

Help with programming Work (Summation) (Complete beginner)

$
0
0
So I'm currently using Visual Studio 2013, and I was left for homework as a beginner programmer to calculate two summations. First the summation of k to n. k=1 and the equation being k^3.
The parameter would be n and I need to printf the results for n=5, 33, 100, 442, 3456.
I'm honestly not sure how to do this and I need help! I'm completely lost T_T. I know that some of the numbers are big values so float or long should be used but I have no idea how to define these as of yet.

Another is to find the summation
(n)
(k) <<-- one big paranthesis

for values k=8 and n=10, 21, 35, 46, 68

Can anyone give me a lead on these two problems? Or help me out? :(
Any help at all is appreciated! as I have no idea how to start excluding <stdio.h> and int main :(
Also, do I have to repeat a new function for every number for n?

Thank you!

No I'm not asking for someone to do the work. Literlaly I just need help with what functions to use or what to put at the beginning just to give me an idea so I can at least start!

This is what I have so far for something I did differently

// Seung
// Tarea 4
// A01021720
// Factoriales Sumatorias


#include <stdio.h>

int suma1
{
int n = 5; // Defino e Inicializo la variable
long sumatoria = 1; // definición e inicialización del resultado

while (n <= 5)
{
sumatoria = sumatoria + n; //sumatoria = sumatoria + n;
n++; //n = n + 1;
}
return sumatoria;
}


int main()
{
int n = 5;
long sumatoria = 1;

while (n <= 5)
{
sumatoria = sumatoria + n; //sumatoria = sumatoria + n;
n++; //n = n + 1;
}
printf("Sumatoria de k^3: %ld\n", sumatoria);
return 1;
}

[RESOLVED] Linked List

$
0
0
HTML Code:

#include<iostream>
#include <cstdlib>

using namespace std;

char name[20];

class room
{
 public:
    int data;
    room* next;
};

class Pointers
{
        public:
        Pointers()
        {
                top = NULL;
                count=0;
        }

        bool empty()
        {
                if(count==0)
                        return true;
                else
                        return false;
        }
//ap is after_posistion
        void insert(int ap, int element)
        {
                room *newelement = new room;

                if(top == NULL)
                {     
                        newelement->data = element;
                        newelement->next = NULL;
                        top = newelement;
                        count++;
                }
                else
                {
                        room *temp;
                        temp = top;
                        for(int i=0;i<ap; i++)
                                temp=temp->
next;

                        newelement->data = element;
                        newelement->next = temp->next;
                        temp->next = newelement;
                        count++;
                }
        }

        void remove(int ap)
        {
                room *temp;
                temp = top;
                for(int i=0;i<ap;i++)
                        temp=temp->
next;

                room * old = temp->next;
                temp->next = old->next;
                count--;
                delete(old);
        }


        void print()
        {
                room *temp;
                temp = top;
                while(temp!=NULL)
                {
                        cout<<temp->data<<",";
                        temp=temp->
next;
                }
        }
        private:
                room *top;
                int count; //head
                int stackData;     
};

int main() { 
    Pointers *sl = new Pointers(); 
    sl->insert(0,10);
    sl->insert(10,20);
    sl->insert(20,30);
    sl->insert(20,40);
    sl->insert(30,50);
    sl->insert(50,60);
    sl->insert(5,70);
    sl->remove(30);
    sl->remove(10);
    sl->remove(50);
    sl->print();

    cin>>name;
    return 0;
}

Line 75 breaks due to temp=NULL. I think using while(temp!=NULL) would help fix it instead of for loop but other than that no clue. Simple linked list getting in two numbers first being the position in the list, second being the value

My binary tree class

$
0
0
Hello guys,

I wanted to solve an exercise which is as follows. You can look at it here (http://books.google.com/books?id=We2...epage&q&f=true) exercise no.11 :)

It says: "Define a Binary_tree class derived from Shape. Give the number of levels as a parameter (level == 0 means no nodes, level == 1 means one node, level ==2 means one top node with two sub-modes, level ==3 means one top node with two sub-modes each with two sub-modes, etc.). Let a node be presented as a small circle. Connect the nodes by lines (as is conventional). P.S. In computer science trees grow downward from a top node (amusingly, but logically, often called the root).".

I wrote the below code:

Code:

#include <Simple_window.h>
#include <iostream>

class Binary_tree : public Shape
{
public:
        Binary_tree(Point, int);
        void draw_lines() const;
        Point f(int i) {return point(i);}
        Point ret_points(int pn) { return point(pn); }

private:
        int level;               
};

//*******************

Binary_tree::Binary_tree(Point p, int le):level(le)
{
        add(Point(p));
        int dis_x_r = 150, dis_x_l = 150, dis_y = 40;
        int w1 = 2, k = 1, l = 1, m = 1, scale = 63;
        for(int i=1; i<level-1; i++)
                w1 *= 2;

        for(int j=1; j<w1; j++)
        {
                while(m<l)
                  {
                        k *= 2;
                        m++;
                  }
                                if(j == k) {
                                        if(j > 1)
                                {
                  dis_x_r -= scale;
                      dis_x_l -= scale;
                              scale -= 6;
                                }
                                        l++; }
                       
          add(Point(point(number_of_points()-j).x-dis_x_l,  point(number_of_points()-j).y+dis_y));
          add(Point(point(number_of_points()-j-1).x+dis_x_r, point(number_of_points()-j-1).y+dis_y));
        }
       
}

//********************************

void Binary_tree::draw_lines() const
{
        int k = 1, w2 = 2;
        for(int i=1; i<level-1; i++)
                w2 *= 2;
        for(int j=w2-1; j>0; j--)
        {
          fl_circle(point(number_of_points()-j-w2).x,    point(number_of_points()-j-w2).y,3);
          fl_line  (point(number_of_points()-j-w2).x,    point(number_of_points()-j-w2).y, point(number_of_points()-j-w2+k).x,
                        point(number_of_points()-j-w2+k).y);
          fl_circle(point(number_of_points()-j-w2+k).x,  point(number_of_points()-j-w2+k).y,3);
          fl_line  (point(number_of_points()-j-w2).x,    point(number_of_points()-j-w2).y, point(number_of_points()-j-w2+k+1).x,
                        point(number_of_points()-j-w2+k+1).y);
          fl_circle(point(number_of_points()-j-w2+k+1).x, point(number_of_points()-j-w2+k+1).y,3
                  );
          k++;
        }
}

//*************************

int main()
{
        int lev;
        cout <<" Please enter the level of binary tree: ";
        cin >> lev;

        Simple_window win(Point(100,100), 1000, 600, "Binary_tree");
        Point p(500,50);
       
          if(lev == 0)
          {
                Text t(Point(400,50),"There is no node!");
            win.attach(t);
                win.wait_for_button();
          }
          else if(lev == 1)
          {
                  Circle c(Point(p),3);
              c.set_style(Line_style(Line_style::solid,1));
              win.attach(c);
                  win.wait_for_button();
          }
         
          else {
                      Binary_tree bt(p,lev);
                          win.attach(bt);
                          win.wait_for_button();       
          }           
}

What do you think about this code as an answer to the exercise. Is it possible to write a better one in a short time? It took than me hours!

PS: I read PPP book (the book I gave its link above), that is, whole of my C++ knowledge is from it and have read it only until end of chapter 14. Now if you want to help, please, put yourself in place of me. Think you have been taught C++ just by those 14 chapters. This is my situation. What would be your answer to this exercise in this situation?
Answers which utilize facilities introduced in later chapters are not helpful for me, because I need to solve the exercise by knowledge of these first 14 chapters which I have been taught! :)

[RESOLVED] beginner in c++ help needed, thanks

$
0
0
hi, i'm trying to solve a basic assignment, but cannot get it right. anyone has any idea why my test_input() function is not working properly?

My assignment:
Make a new projekt called “my-sudoku” in eclipse
Make the program print out to the screen “Welcome to my sudoko – input row,col,val”
Get input using cin and make use of integers row,col,val
Display the values by using cout
Debug the program and run it, see what happens on the console.
In you’re my-sudoku project make a function called get_input() that will take 3 integers from the user (row,col,val). The function shall be called from main
Make a function test_input(), which will test if the inputs are in the legal range of 1..9. The function should be called from get_input
Print a message to the screen whether the inputs are legal or not.

My code:

#include <iostream>
using namespace std;

void get_input();
void test_input();

int main()
{
cout<< "Welcome to my sudoku – input row, col, val \n";
get_input();
return 0;
}

void get_input()
{
int row, col, val;
cout<< "Please enter number of rows: ";
cin>> row;
test_input();
cout<< "Please enter number of columns: ";
cin>> col;
test_input();
cout<< "Please enter value: ";
cin>> val;
test_input();
}

void test_input()
{
int row, col, val, number;
row=col=val=number;
if(0<number<10)
cout << "Allowed number. \n";
else
cout << "Number not allowed. Please insert a number between 1 and 9. \n";
}

Thanks for your help.

How to Enable/Disable Menu Item 2 in OnUpdate Handler of Menu Item 1?

$
0
0
I have two menu items. When item 1 is disabled, I want item 2 to be disabled as well. In the OnUpdate handler of menu item 1, I have tried to use "t_pMenu = pCmdUI->m_pMenu;", "t_pMenu = pCmdUI->m_pSubMenu;" and "t_pMenu = pCmdUI->m_pParentMenu;" but I always get NULL t_pMenu. How can I achieve this purpose?

Code:

void CDummyView::OnUpdateMenuItem1(CCmdUI* pCmdUI)
{
        if(m_bShowMenuItem1) {
                pCmdUI->Enable(TRUE);
                CMenu * t_pMenu = pCmdUI->m_pSubMenu;
                if(t_pMenu != NULL)
                        t_pMenu->EnableMenuItem(ID_MENU_ITEM2, MF_ENABLED);
        }
        else {
                pCmdUI->Enable(FALSE);
                CMenu * t_pMenu = pCmdUI->m_pParentMenu;
                if(t_pMenu != NULL)
                        t_pMenu->EnableMenuItem(ID_MENU_ITEM2, MF_GRAYED);
        }
}

void CDummyView::OnUpdateMenuItem2(CCmdUI* pCmdUI)
{
        ...
}

Thanks,
Brian

Installing FLTK on VS 2013

$
0
0
Hello all,

Is there a correct way of installing FLTK (say. 1.3.2) on vs 2013 and get it ran below code successfully?

Code:

#include <Simple_window.h>

int main()
{
        Simple_window win(Point(100, 100), 1000, 600, "test");
        Circle c(Point(200, 200), 50);
        win.attach(c);
        win.wait_for_button();
}

I got this error:
Code:

Error        16        error C2440: 'return' : cannot convert from 'std::ifstream' to 'bool'        c:\program files\microsoft visual studio 12.0\vc\include\graph.cpp        371        1        Win32Project1

Help with Microsoft Visual C++

$
0
0
Name:  Untitled6.jpg
Views: 65
Size:  30.0 KB I'm new to this program and I'm having trouble he's asking for prices, sales tax but I don't know how to format them into the code. What do I use? How do I run and compile? I have a screenshot.




Code:

1) Create a CPP file named lab2 in Visual C++  with the source file containing the following lines.
//**************************************************************
//
// File Name: lab2.cpp
//
// A Program to calculate the sales tax and final sales
//                price of items in a retail environment
//
// Programmer: “Your Name Goes Here”
//
// Date Written: today’s date
//
// Date last revised:
//
//**************************************************************

#include <iostream> // need cin, cout and endl
#include <iomanip> // need setprecision
using namespace std;

#define pause system(“pause”)  // stop the screen from scrolling
#define cls  system(“cls”)    // clear the screen

const double SALES_TAX_RATE = 0.0875; // current sales tax rate
                                    //  in Erie County NY, USA

int main ()
  {
      double price,        // price of the item
            salesTax,  // sales tax on the item
            finalPrice; // price of the item plus sales tax

      // ask user for item price

      cout << "Please enter the current price of the item $"  ;

      // grab the price info

      cin >> price;

      cout << endl ; // skip a line for readability

        pause;        // let the user read the screen
      cls;          // clear the screen

      // Now do the calculations

      salesTax = price * SALES_TAX_RATE;
      finalPrice = price + salesTax;

      // Now do some pretty printing of the results

      cout << "The price of the item was " << price
          << "\n\n\n";

      cout << "The sales tax on the item was "
          << salesTax << "\n\n";

      cout << "The price including the sales tax for the item was ";
      cout << finalPrice << "\n" << endl;
     
      return 0;

    }

note if you are using a MAC IDE:

A) DO NOT USE
#define pause system(“pause”) // stop the screen from scrolling

INSTEAD USE:

cout << "\nPress the enter key to continue.\n";
cin.get();

IN PLACE OF THE
pause;
LINE

B) DO NOT USE

#define cls system(“cls”) // clear the screen

INSTEAD USE:

for(int k = 0; k < 25; k++)
cout << endl;

IN PLACE OF THE
cls;

LINE

END OF THE MAC SECTION DISREGARD IF NOT USING A MAC


2) Build the executable file. Locate and fix any errors and rebuild the executable.

3) Run the program using the input value of 1.9.

4) Rerun the program trying other values.

5) Notice the output does not quite look like a “money” value.

6) Modify the program to include a “$” output to pretty up the output.

7) Notice that the output still does not look like “money” because $1.9 does not look right but $1.90 does.

8) Add lines of code to have the money values printed with 2 decimal places.(note see page 114 in your book)

10) Rerun the program, now notice how the output lines are “pretty”.
Attached Images
 

Tooltips not working for all controls in CFormView derived class

$
0
0
I can't get tooltips to show up for the windows I want in my CFormView derived class. I have copied the code from the MSDN entry on EnableToolTips(). But only two windows respond with a tooltip:

CONTROL "Tree1",IDC_TESTPLANS,"SysTreeView32",TVS_HASBUTTONS | TVS_HASLINES | TVS_EDITLABELS | TVS_SHOWSELALWAYS | WS_BORDER | WS_HSCROLL | WS_TABSTOP,1,36,85,91
CONTROL "Tab1",IDC_TABCMD,"SysTabControl32",0x0,101,0,239,181

Other windows do not respond. For these windows my function designed to catch the TTN_NEEDTEXTW and TTN_NEEDTEXTA messages is not called. Windows such as

LISTBOX IDC_TESTPLANNAMES,0,119,48,40,LBS_SORT | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP
PUSHBUTTON "",IDC_BTN_COPY,105,177,24,24,BS_ICON

Why wouldn't the messages be sent for those windows? I'm using the code

ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, &CCntlrView::OnTtnNeedText)
ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, &CCntlrView::OnTtnNeedText)

(CCntrlView is the name of my class derived from CFormView.) And as I pointed out, I'm using the code straight from the example given in MSDN for CWnd::EnableToolTips(), with the only difference being that all my controls are created in the rc file as shown above.

Any help appreciated.

Thanks,
Gary

What technologies to use for modern Windows client development?

$
0
0
I developed several C++/MFC-based client applications for a client many years ago and have been maintaining and enhancing them since then. They are basically business apps with lots of form entry, database functionality, printing, connections with web services, report generation, custom list and grid controls and some degree of skinning control for customizing for particular clients. MFC was used for all of this functionality.
I'd like to do a rewrite to make these apps more maintainable, but I'd also like to upgrade the rather boring UI using modern approaches. I know Microsoft still maintains MFC in recent Visual Studio releases, but I know they push development with WPF/C#/XAML/.NET. I definitely do not need to do a Metro app nor mobile app since these clients only need to run on XP/Win7/Win8 desktops. I just want to make sure that WPF is the way to go for developing today's client apps?

Help with clearing out variables

$
0
0
Below is my code. It runs and it looks like it is doing MOSTLY what I am wanting. I cannot seem to figure out if I say Y to do you want to continue, it
calculates the total number of months from my first go-round with the second. How do I clear out my variables?

Also, am I counting the number of months correctly?
Lastly, my total interest isn't calculating corrctly.
Code:

#include <iostream>
#include <cmath>
using namespace std;

double GetMonthlyIntrest (double OpenBalance,double rate);
bool ContinuePgm();

int main ()
{
       
        double StartingBalance,rate,amount,OpenBalance,IntPmt,TotalInt=0.0;
        int totalmonths=0;
       
        do
                {
                cout << "Enter Starting Loan Amount: ";
                cin >> StartingBalance;
                cout  <<  "\nEnter the interest rate of your loan: ";
                cin >> rate;
               
                amount=StartingBalance/20.0;

                OpenBalance=StartingBalance;

                cout.setf(ios::fixed);
                cout.setf(ios::showpoint);
                cout.precision(2);

                while (OpenBalance>=amount)
                        {
                        IntPmt=GetMonthlyIntrest(OpenBalance,rate);
                        TotalInt = TotalInt +1;
                        OpenBalance=OpenBalance-(amount-IntPmt);
                        totalmonths = totalmonths +1;
                       
                        cout << "\nMonthly Payment: \t$"
                                << amount;
                        cout << "\tInterest Paid: \t$";
                        cout << IntPmt;
                }

                if (OpenBalance>0)
                        {
                        IntPmt=(OpenBalance*(rate/100))/12;
                        OpenBalance=OpenBalance+IntPmt;
                        totalmonths = totalmonths +1;
                        TotalInt = TotalInt +1;

                        cout << "\nMonthly Payment: \t$"
                                << OpenBalance;
                        cout << "\t\tInterest Paid: \t$";
                        cout << IntPmt;
                }

                cout << "\nTotal Number of Months: "
                        << totalmonths;

                cout << "\tTotal Interest Payment Paid: "
                        << TotalInt;


                }while (ContinuePgm ());
               
        return 0;
}

double GetMonthlyIntrest (double OpenBalance,double rate)
{
        double IntPmt;

        IntPmt=(OpenBalance*(rate/100)/12);

        return(IntPmt);
}

//below is defining the ContinuePgm function
bool ContinuePgm()
{
        char Ans;
        cout << "\n\nDo you want to continue?";
        cin >> Ans;

        if (Ans=='Y'||Ans=='y')
                return true;
        else
        return false;
}

Totals or my formula to caculate is not working

$
0
0
My code is below:

Total Interest ends up as my last Monthly Payment amount instead of adding up all Interest Paid - What am I doing wrong?


Total Paid isn't calculating correcly either - What am I doing wrong?


I suspect both are very similar problems. I've tried several different calculations, but cannot figure this out.

#include <iostream>
#include <cmath>
using namespace std;

double GetMonthlyIntrest (double OpenBalance,double rate);
bool ContinuePgm();

int main ()
{

double StartingBalance,rate,amount,OpenBalance,IntPmt,TotalInt=0.0,GrandTotal=0.0;
int totalmonths=0;

do
{
cout << "Enter Starting Loan Amount: ";
cin >> StartingBalance;
cout << "\nEnter the interest rate of your loan: ";
cin >> rate;

amount=StartingBalance/20.0;

OpenBalance=StartingBalance;

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

totalmonths=0;
TotalInt=0.0;
GrandTotal=0.0;

while (OpenBalance>=amount)
{
IntPmt = GetMonthlyIntrest(OpenBalance,rate);
OpenBalance = OpenBalance-(amount-IntPmt);
totalmonths = totalmonths +1;
TotalInt = TotalInt + IntPmt++;
GrandTotal = GrandTotal + amount;

cout << "\nMonthly Payment: \t$"
<< amount;
cout << "\t\tInterest Paid: \t$";
cout << IntPmt;
}

if (OpenBalance>0)
{
IntPmt=(OpenBalance*(rate/100))/12;
OpenBalance=OpenBalance+IntPmt;
totalmonths = totalmonths +1;
TotalInt = TotalInt + IntPmt++;
GrandTotal = GrandTotal + amount;

cout << "\nMonthly Payment: \t$"
<< OpenBalance;
cout << "\t\tInterest Paid: \t$";
cout << IntPmt;
}

cout << "\n\nTotal Number of Months: "
<< totalmonths;

cout << "\t\tTotal Interest Payment Paid: $"
<< TotalInt;

cout << "\n\nTotal Paid: $"
<< GrandTotal;

}while (ContinuePgm ());

return 0;
}

double GetMonthlyIntrest (double OpenBalance,double rate)
{
double IntPmt;

IntPmt=(OpenBalance*(rate/100)/12);

return(IntPmt);
}

//below is defining the ContinuePgm function
bool ContinuePgm()
{
char Ans;
cout << "\n\nDo you want to calculate another loan?";
cin >> Ans;

if (Ans=='Y'||Ans=='y')
return true;
else
return false;
}

Using Comparables.

$
0
0
Hi,
I lately open up a C++ project (Visual C++ project) which was converted from Java a few years ago.
This converted snippet has something called the object Object which is not compilable on VC++
Any ideas I can change this class to C++ compatible? Basically, it is checking the identity of the objects.
Any pointers? I don't think I can replace object or object* with void*, what functions are available in place of these functions? don't know how to call it.
Code:

class Point
{
        public:
        const int x;
        const int z;

        Point(int x, int z);
        virtual bool Equals(object *o);
        virtual bool Equals(Point *other);

        virtual std::string ToString();
};

Definitely it's not nice. But I need the source code to do my other projects.
Thanks
Jack

HI I need help converting my program from a strucc to a class

$
0
0
I am not exactly sure how to do this and i keep running into problems. This is my code here that works.
Code:

#include<iostream>
using namespace std;

struct record
{
        double quiz1;
        double quiz2;
        double midyear, midyear_one;
        double final, final_one;
        double quiz_average;
        char final_grade;
        double total_grade;
};
void instructions();

void input(record& the_grades);

void output(record& the_grades);

int main()
{
        char run_again;

        record grades;
        instructions();
        do
        {
                input(grades);
                output(grades);
                cout << endl << endl;
                cout << "Run again?:";
                cout << "(enter Y or N)";
                cout << endl;
                cin >> run_again;
        } while ((run_again == 'y') || (run_again == 'Y'));
        cout << "<program end>";
        cout << endl << endl;
        system("pause");
        return 0;
}

void instructions()
{
        cout << "Welcome to the program student record";
        cout << endl << "this program takes in 2quizes, a final and midyear";
        cout << endl << "and then calculates the average by what they are worth by";
        cout << endl << "the quizes together are worth 25% and midyear counts for 25%";
        cout << endl << "and the final counts for 50%";
        cout << endl;
}
void input(record& the_grades)
{
        cout << endl;
        cout << "Enter quiz 1 grade out of 10 points:\n";
        cin >> the_grades.quiz1;
        while (the_grades.quiz1 > 10)
        {
                cout << "ERROR!: Invalid Value";
                cout << endl;
                cout << "Re- Enter Value for quiz 1:\n";
                cin >> the_grades.quiz1;
                cout << endl;
        }
        cout << endl;
        cout << "Enter quiz 2 grade out of 10 points:\n";
        cin >> the_grades.quiz2;
        while (the_grades.quiz2 > 10)
        {
                cout << "ERROR!: Invalid Value";
                cout << endl;
                cout << "Re- Enter Value for quiz 2:\n";
                cin >> the_grades.quiz2;
                cout << endl;
        }
        cout << "Enter midyear Exam grade out of 100 points:\n";
        cin >> the_grades.midyear;
        while (the_grades.midyear > 100)
        {
                cout << "ERROR!: Invalid Value";
                cout << endl;
                cout << "Re- Enter Value for Midyear Exam:\n";
                cin >> the_grades.midyear;
                cout << endl;
        }
        cout << endl;
        cout << "Enter Final Exam grade out of 100 points:\n";
        cin >> the_grades.final;
        while (the_grades.final > 100)
        {
                cout << "ERROR!: Invalid Value";
                cout << endl;
                cout << "Re- Enter Value for Final Exam:\n";
                cin >> the_grades.final;
                cout << endl;
        }
        cout << endl;
}
void output(record& the_grades)
{
        the_grades.quiz_average = (((the_grades.quiz1 / 10) + (the_grades.quiz2 / 10)) / 2) * .25;
        the_grades.final_one = (the_grades.final / 100) * .5;
        the_grades.midyear_one = (the_grades.midyear / 100) *.25;
        the_grades.total_grade = (the_grades.quiz_average + the_grades.final_one + the_grades.midyear_one) * 100;

        cout << endl << endl;
        cout << "Quiz1: " << (the_grades.quiz1 / 10) * 100 << "% ";
        cout << endl;
        cout << "Quiz2: " << (the_grades.quiz2 / 10) * 100 << "% ";
        cout << endl;
        cout << "Midyear exam: " << the_grades.midyear << "/100";
        cout << endl;
        cout << "Final exam: " << the_grades.final << "/100";
        cout << endl;
        cout << "Final grade: " << the_grades.total_grade << " %";
        cout << endl;
        cout << "Letter grade: ";
        if (the_grades.total_grade <= 60.0)
        {
                cout << "F";
        }
        if ((the_grades.total_grade >= 60.0) && (the_grades.total_grade < 70.0))
        {
                cout << "D";
        }
        if ((the_grades.total_grade >= 70.0) && (the_grades.total_grade < 80.0))
        {
                cout << "C";
        }
        if ((the_grades.total_grade >= 80.0) && (the_grades.total_grade < 90.0))
        {
                cout << "B";
        }
        if (the_grades.total_grade >= 90.0)
        {
                cout << "A";
        }
        cout << endl;

}

please help

I was constantly calling ostrstream? But private member access violation..

$
0
0
Code:

std::ostrstream oss;
oss << "path for " << unit << "\n\t" << path;
puts(oss.str());

Code:

class ostrstream
        : public ostream
        {        // output stream associated with a character array
public:
        typedef ostrstream _Myt;
        typedef ostream _Mybase;
        typedef strstreambuf _Mysb;

        __CLR_OR_THIS_CALL ostrstream()
                : ostream(&_Strbuffer), _Strbuffer()
                {        // construct with empty character array
                }

        __CLR_OR_THIS_CALL ostrstream(char *_Ptr,
                streamsize _Count,
                ios_base::openmode _Mode =
                        ios_base::out)
                : ostream(&_Strbuffer),
                        _Strbuffer(_Ptr, _Count,
                                _Ptr == 0 || (_Mode & ios_base::app) == 0
                                        ? _Ptr : _Ptr + _CSTD strlen(_Ptr))
                {        // construct with [_Ptr, _Ptr + _Count)
                }

        __CLR_OR_THIS_CALL ostrstream(_Myt&& _Right)
                : _Mybase(&_Strbuffer)
                {        // construct by moving _Right
                _Assign_rv(_STD forward<_Myt>(_Right));
                }

        _Myt& __CLR_OR_THIS_CALL operator=(_Myt&& _Right)
                {        // move from _Right
                _Assign_rv(_STD forward<_Myt>(_Right));
                return (*this);
                }

        void __CLR_OR_THIS_CALL _Assign_rv(_Myt&& _Right)
                {        // move from _Right
                if (this != &_Right)
                        {        // different, swap base and buffer
                        _Strbuffer.clear();
                        this->swap(_Right);
                        }
                }

        void __CLR_OR_THIS_CALL swap(_Myt& _Right)
                {        // swap with _Right
                if (this != &_Right)
                        {        // different, swap base and buffer
                        _Mybase::swap(_Right);
                        _Strbuffer.swap(_Right._Strbuffer);
                        }
                }

        void __CLR_OR_THIS_CALL swap(_Myt&& _Right)
                {        // swap with _Right
                _Assign_rv(_STD forward<_Myt>(_Right));
                }

        virtual __CLR_OR_THIS_CALL ~ostrstream()
                {        // destroy an ostrstream
                }

        _Mysb *__CLR_OR_THIS_CALL rdbuf() const
                {        // return pointer to character array buffer
                return ((_Mysb *)&_Strbuffer);
                }

        void __CLR_OR_THIS_CALL freeze(bool _Freezeit = true)
                {        // freeze or unfreeze writing
                _Strbuffer.freeze(_Freezeit);
                }

        char *__CLR_OR_THIS_CALL str()
                {        // freeze and return pointer to character array
                return (_Strbuffer.str());
                }

        streamsize __CLR_OR_THIS_CALL pcount() const
                {        // return size of writable character array
                return (_Strbuffer.pcount());
                }

private:
        _Mysb _Strbuffer;        // the string buffer
        };

Today, I just received this new fresh error, I was constantly using them, but just come to know
it is a private access violation as the last error of my program.
Did I use it in the wrong way?
Thanks
Jack

I'd like to rewrite this comparison method.

$
0
0
Code:

bool Unit::Equals(object *o)
{
                               
        return (dynamic_cast<Unit*>(o) != 0) ? equals(static_cast<Unit*>(o)) : false;
}

If I use
Code:

bool Unit::operator==(const Unit& rhs)
What will the body look like?
Keep asking questions today...
Thanks
Jack

More CopyFile Problems

$
0
0
Codeguru and the web generally is replete with posts on problems encountered using Copyfile.

see: http://forums.codeguru.com/showthrea...light=CopyFile

My problem is that CopyFile in an MFC setting appears to work, that is the destination file shows up where it should but is always empty. I've checked the file paths and they appear to be correct. bError here always returns 0 indicating that the function failed, yet dwError here always returns 0. I have tried using CopyFileEx with exactly the same result. My target files in both instances are *.xml files, but I believe that the file type is irrelevant.

Code:

        BOOL bError = CopyFileW(csDBFilepath, m_csPathname, FALSE);
        DWORD dwError = GetLastError();  _RPT1(0, "dwError = %d\n", dwError);

However, when I use the same files and CopyFile in a Win32 app, it always works. I have attached a small example program to show that identical coding works in Win32.

Any help or comments greatly appreciated. Thanks.
Attached Files

Visual Studio cannot find relative header file

$
0
0
For a while, I have been running a Windows 7 Visual Studio 2012 CPP project fine. However, today, all of a sudden, it has stopped being able to read any header files that are in relative directories. I cannot think what I have done to make this happen.

It seems to be an issue with Visual Studio as a whole, rather than my individual project, because I have created a new simple project and I am having the same problem. So, I have a CPP project at `C:/Projects/TestProject`. Then, I have a header file called `test_header.hpp`, which is located at `C:/Headers`. In `TestProject`'s project settings, I have added the directory `../../Headers` to `Additional Include Directories`. Then, my main functions is as follows:

Code:

#include "test_header.hpp"
int main()
{
    return 0;
}

Which gives me the error:

Code:

Error        1        error C1083: Cannot open include file: 'test.hpp': No such file or directory        c:\projects\testproject\main.cpp        1        1        TestProject
Any ideas on what is going on here? Is there some global Visual Studio setting that is responsible for setting up these relative directories? Just in case the relative directory was not correct, I also tried a load of others, such as `../Headers` and `../../../Headers`, but these gave the same errors.

doublt linked list and basic text editor

$
0
0
So for a school assignment I'm supposed to make a basic text editor using a doubly linked list, I have pretty much written most of it but keep coming across several problems. In certain places,all marked in the code, I get the error "expected a declaration" ive looked online and nothing ive found helps. And secondly I also get the error" declaration has no storage class or type specifier" but i havent been able to find anything that helps either. If anyone could help me fix these id greatly appreciate it



Code:

// assignment 2-2.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <assert.h>
#include <string>
#include <windows.h>
#include <list>

using namespace std;

template <class Node_entry>
struct Node {
// data members
Node_entry entry;
Node<Node_entry> *next;
Node<Node_entry> *back;
// constructors
Node( );
Node(Node_entry, Node<Node_entry> *link_back = NULL,
Node<Node_entry> *link_next = NULL);
};

template <class List_entry>
class List {
public:
// methods of the List ADT
List( );
        int size( ) const;
        bool full( ) const;
        bool empty( ) const;       
        void clear( );
        error_code traverse(void (*visit)(List_entry &));
        error_code retrieve(int position, List_entry &x) const;
        error_code remove(int position, List_entry &x);
        error_code insert(int position, const List_entry &x);
protected:
// data members for a contiguous list implementation
        int count=0;
        List_entry entry[max_list];
        mutable int current_position;
        mutable Node<List_entry> *current;

        void set_position(int position) const;
}


template <class List_entry>
int List<List_entry>::size( ) const
{
return count;
}

template <class List_entry>
void List<List entry>::set_position(int position) const
{
if (current position <= position)
        for ( ; current position != position; current position++)
                current = current->next;
else
        for ( ; current position != position; current position−−)
                current = current->back;
}

template <class List_entry>
error_code List<List_entry>::insert(int position, const List entry &x)
        {
Node<List_entry> *new_node, *following, *preceding;
if (position < 0 || position > count) return range_error;

if (position == 0) {
        if (count == 0) following = NULL;
        else {
        set_position(0);
        following = current;
                }
        preceding = NULL;
        }
else {
        set_position(position − 1);
        preceding = current;
        following = preceding->next;
        }
new_node = new Node<List_entry>(x, preceding, following);
if (new_node == NULL)
        return overflow;
if (preceding != NULL)
        preceding->next = new_node;
if(following != NULL) following->back = new_node;
current=new_node;
current_position=position;//<-----error declaration has no storage class same for next 2
count++;//<----error
return success;//<-----error
}

int main(int argc, char *argv[ ])
{
if (argc != 3) {
        cout << "Usage:\n\t edit inputfile outputfile" << endl;
        exit (1);
        }
ifstream file_in(argv[1]); // Declare and open the input stream.
if (file_in == 0) {//<<----error Expected a Declartion
        cout << "Cant open input file " << argv[1] << endl;
        exit (1);
        }
ofstream file_out(argv[2]); // Declare and open the output stream.
if (file_out == 0) {//<--same as above
        cout << "Cant open output file " << argv[2] << endl;
        exit (1);
        }
Editor buffer( &file in, &file out);
while (buffer.get_command())//<<----error Expected a Declartion
        buffer.run_command();
}

class Editor: public List<String> {
public:
        Editor(ifstream *file_in, ofstream *file_out);
        bool get_command( );
        void run_command( );
private:
        ifstream *infile;
        ofstream *outfile;
        char user_command;
// auxiliary functions
        error_code next_line( );
        error_code previous_line( );
        error_code goto_line( );
        error_code insert_line( );
        error_code substitute_line( );
        error_code change_line( );
        void read_file( );
        void write_file( );
        void find_string( );
}//<<----error Expected a Declartion

Editor::Editor(ifstream *file in, ofstream *file out)
{
infile = file in;
outfile = file out;
}

bool Editor:: get_command( )
{
        if (current != NULL)
        cout << current_position << " : "<< current->entry.c str( ) << "\n??" << flush;
else
        cout << "File is empty.\n??" << flush;
cin >> user_command; // ignores white space and gets command
user_command = tolower(user_command);//<-- error "user_command has no storage class
while(cin.get( ) != '\n')//<<----error Expected a Declartion
; // ignore user’s enter key
if(user_command == 'q')//<<----error Expected a Declartion
        return false;
else//<<----error Expected a Declartion
        return true;
}

template <class List_entry>
void Editor::run_command( )
{
string temp_string;
cout << "Press h or ? for help or enter a valid command: ";

if(user_command=='b'){
        if (empty( ))
                cout << " Warning: empty buffer " << endl;
        else
                while (previous_line( ) == success);
        goto point;;}
if(user_command=='c'){
        if (empty( ))
                cout << " Warning: Empty file" << endl;
        else if (change_line( ) != success)
                cout << " Error: Substitution failed " << endl;
        goto point;;}
if(user_command=='d'){
                if (remove(current_position, temp_string) != success)
                        cout << " Error: Deletion failed " << endl;
                goto point;;}
if(user_command=='e'){
        if(empty())
                cout<<"Warning: Buffer is empty"<<endl
        else
                while (next_line( ) == success)
                        ;
        goto point;}
if(user_command=='f'){
        if (empty( )) cout << " Warning: Empty file" << endl;
        else
                find_string( );
        goto point;}//<<----error Expected a Declartion
if(user_command=='g'){
        if (goto_line( ) != success)
                cout << " Warning: No such line" << endl;
        goto point;;}
if(user_command=='?'||user_command=="h"){
        cout << "Valid commands are: b(egin) c(hange) d(el) e(nd)"
        << endl
        << "f(ind) g(o) h(elp) i(nsert) l(ength) n(ext) p(rior) " << endl
        << "q(uit) r(ead) s(ubstitute) v(iew) w(rite) " << endl;}
if(user_command=='i'){
        if (insert_line( ) != success)
                cout << " Error: Insertion failed " << endl;
        goto point;;}
if(user_command=='l'){
        cout << "There are " << size( ) << " lines in the file." << endl;
        if (!empty( ))
                cout << "Current line length is "<< strlen((current->entry).c_str( )) << endl;
        goto point;;}
if(user_command=='n'){
        if (next_line( ) != success)
                cout << " Warning: at end of buffer" << endl;
        goto point;;}
if(user_command=='p'){
        if (previous_line( ) != success)
        cout << " Warning: at start of buffer" << endl;
        goto point;;}
if(user_command=='r'){

        read_file( );
        goto point;;}
if(user_command=='s'){
        if (substitute_line( ) != success)
                cout << " Error: Substitution failed " << endl;
        goto point;;}
if(user_command=='v'){

        traverse(write);
        goto point;;}
if(user_command=='w'){

        if (empty( ))
                cout << " Warning: Empty file" << endl;
        else
                write_file( );
        goto point;;}
point:
       

}
void Editor : : read file( )
{
bool proceed = true;
if (!empty( )) {
        cout << "Buffer is not empty; the read will destroy it." << endl;
        cout << " OK to proceed? " << endl;
        if (proceed = user says yes( )) clear( );
}
int line_number = 0, terminal_char;
while (proceed) {
        String in_string = read_in(*infile, terminal_char);
        if (terminal char == EOF) {
                proceed = false;
                if (strlen(in_string.c_str( )) > 0) insert(line_number, in_string);
                        }
        else insert(line_number++, in_string);
        }
}
Error code Editor : : insert line( ){
int line number;
cout << " Insert what line number? " << flush;
cin >> line_number;
while (cin.get( ) != 'n');
cout << " What is the new line to insert? " << flush;
String to insert = read in(cin);
return insert(line number, to insert);
}

How to raise priority of MIDI input callbacks? Thread pools etc.

$
0
0
Hi,

I'm the author of a realtime MIDI software called ChordEase which makes use of the MIDI aspects of the multimedia API, specifically MIDI input callbacks. In XP and before, these callbacks originated in the kernel and therefore had realtime priority by definition, but from Vista on, they originate in thread pool threads, and have a priority of zero. This is a problem because at priority zero they can be blocked by the GUI thread, causing serious latency, and I have proved that such blocking occurs.

I have experimented with raising the callback thread priority, using either of the following methods: 1) calling SetThreadPriority within the MIDI input callback function, and then setting a flag so that it isn't done repeatedly, or 2) creating a DLL that catches thread creation via DLL_ATTACH_THREAD in DllMain, and calling SetThreadPriority there. The first method is slightly wasteful since the flag has to be tested for every MIDI input event, but it also has the advantage of only affecting the MIDI input threads, whereas the second method affects all threads in the pool regardless of what they're used for. Neither method appears to cause any harmful effects but they make me nervous*. Other possible methods would include 3) using the thread pool API to raise the priority of the pool (assuming I could gain access to the pool handle somehow), or 4) permanently lowering the priority of the GUI thread, which I'm very reluctant to do because of the risk of unintended consequences.

I'm assuming the MIDI input callbacks are using threads in the default thread pool though I haven't actually proved this. Assuming that's so, are these threads private to my application, or is my application sharing them with other applications? Is there a safer way to achieve the result of increasing the priority of MIDI input callbacks? It's incredibly frustrating that MS would change the behavior of MIDI input callbacks so drastically without even telling anyone, but that's how it goes!

Best regards,

Chris Korda
http://chordease.sourceforge.net/

*See for example theses warnings about changing thread pool priorities on Hari's blog:
http://blogs.msdn.com/b/harip/archiv...-priority.aspx

What is the usual maximum size of stack of a win32 program?

$
0
0
I know that if the structure doesn't fit into the stack, it needs to be put onto the heap.
But what is maximum size of a win32 stack in usual case?
Thanks
Jack
Viewing all 3021 articles
Browse latest View live