Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

.i need to know how to rank the students after sorting them in decreasing order of their total...any suggestions..plz reply..

what do you mean by "rank them" ? assign a number like the first one in the list is 1, the second one is 2, and the third (last) one is 3? That should be easy to do, just use the loop counter as shown in RED below.

for(int i=0;i<n;i++)
{
cout<<"\n\n\t "<<rollno[i]<<" \t\t"<<Total[i]<<" \t\t"<<Grade[i] << "  Rank: " << i+1;
 if (Grade[i]=='E')
  {cout<<"\t FAIL" ;}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

ok thatassignment A to everyone was a mistake...but still when i run it..n enter 3 values i can c only 2 ..y is that happening?

I ran the code you posted last and I entered 3 students that that's exactly what it displayed at the end.

What compiler are you using? I used vc++ 2008 Express, replaced iostream.h with iostream (no .h extension) and added using namespace std; But those changes should not have caused the problem you describe.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

lines 71-79: You assign an 'A' to everybody.

I ran the program and got this

PROGRESS REPORT





        Rollno          Total           Grade

         100            380             A

         300            200             E        FAIL

         200            150             E        FAIL
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

you forgot do { for Math Marks on line 54

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

The loops on line 58 and 59 are still wrong. Use the < operator, not the <= operator when counting from 0.

for(int i=0;i<(n-1);i++)     
{  for(int j=(i+1);j<n;j++)
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

You could do something like this:

do
{
    cout<<"Enter English marks  ";
    cin>>english[i];
    if( english[i] > 100)
       cout << "Error\n";
} while( english[i] > 100 );

And if you are going to do that several times just write a function that returns the value

int GetEntry(string prompt)
{
    int value = 0;
    do
    {
          cout << prompt << "\n";
          cin >> value;
          if( value > 100)
              cout << "Error\n";
     } while( value > 100);
    return value;
}

int main()
{
    ...
    English[i] = GetEntry("Enter English Marks");

}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Myself, I would have used a structure for that information so that you can easily sort structures instead of so many simple arrays.

struct student
{
    int total;
    // rest of student info goes here
};

But if you want to leave it the way you have it, then during the swap you have to swap all the arrays, not just the Total array.

for(int i=0; i < (n-1); i++)
{
    for(int j = (i+1); j < n; j++)
    {
       if (Total[j]>Total[i])
       { 
           temp=Total[i];
           Total[i]=Total[j];
           Total[j]=temp;
           temp = Grade[i];
           Grade[i] = Grade[j];
           Grade[j] = temp;
           // etc etc for each of the arrays.
        }//if statement
     }
}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

1) Array elements start counting from 0, not 1. That means the first element of Total is Total[0] and loop counters should count from 0 to but not including the number of elements in the array.

Example: The loop counters beginning on line 58 should be (and that's how I write simple bubble sort algorithm too :) )

for(int i=0; i < (n-1); i++)
{
    for(int j = (i+1); j < n; j++)
    {
         // blabla
    }
}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>>when i save data in different files and ask them to fetch the same data from files but it just show me the data of last file no matters if i enter the name of first file

You have to add some more code to read the file after it is opened on line 62. Your program opens the file then just ignores it.

>>and it is adding average of last student with the current one
You have to reinitialize total to 0 before starting the loop on line 25.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

About the files: I see now that your program creates them. Its not necessary to have an array of file pointers, e.g. FILE *p[2]; . All you need is one and just reuse it. FILE* p; You are asking people to enter the birth date as a single integer -- I don't know about you but I like to enter my birthdate in MM/DD/YYYY or MM-DD-YYYY format and you can't do that with your program. Suggest you change the data type of birthdate to a character array so that you can enter it in normal fashion.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

The indentation of your program is terrible -- hopefully it was just a problem with posting here. So here is a corrected copy

#include<stdio.h>
#include<string.h>
#pragma warning(disable: 4996)

float avg(float);
main()
{
    FILE *p[2];
    int k,students=10,subjects=4,i,j,id_number,date_of_birth,fail=0;
    float marks[100],total=0,avg;
    char name[30],course_enrolled[30],filename[10];
    for(i=1;i<=2;i++)
    {
        printf("filename"); 
        scanf("%s",&filename);
        p[i]=fopen(filename,"w");
        printf("Enter Name of Student\n",p[i]);
        fscanf(stdin,"%s",&name,p[i]);
        printf("Enter Course In Which Student Is Enrolled\n",p[i]); 
        fscanf(stdin,"%s",&course_enrolled,p[i]);
        printf("Enter ID Number Of %s Enrolled in Course %s\n",name,course_enrolled,p[i]);
        fscanf(stdin,"%d",&id_number,p[i]);
        printf("Enter Date Of Birth Of %s Enrolled in Course %s and\n ID-Number is %d\n",name,course_enrolled,id_number,p[i]);
        fscanf(stdin,"%d",&date_of_birth,p[i]);
        for(j=1;j<=4;j++)
        {
            printf("Enter Marks for Subject %d for Student %s\n",j,name);
            fscanf(stdin,"%f",&marks[j]);
            total=total+marks[j];
            if(marks[j]<50)
                fail=fail+1;
            else
                continue;
        } 
        avg=(total/400)*100;
        printf("AVERAGE=%f\n",avg);
        if(avg>=70)
            printf("Grade A\n");
        if(avg>=60&avg<70)
            printf("Grade B\n");
        else if(avg>=50&avg<60)
            printf("Grade C\n");
        else if(avg>=45&avg<50) 
            printf("Grade D\n");
        else if(avg>=40&avg<45)
            printf("Grade E\n");
        else if(avg<40)
            printf("Fail\n");
        if(fail>=2)
            printf("Student is failed and cann;t promote\n");
        else
            continue;
        fclose (p[i]); 
    }
    for(k=1;k<=2;k++)
    {
        printf("Input filename"); 
        scanf("%s",&filename);
        p[k]=fopen(filename,"r");
        fprintf(stdout,"NAME= %s\tCOURSE ENTITLLED= %s\t ID NUMBER= %d\t DATE OF BIRTH= %d\tAVERAGE= %f\n",name,course_enrolled,id_number,date_of_birth,avg);
        fclose (p[k]);
    }
    getch();
}

When I compiled it using VC++ 2008 Express I got several warnings which you need to correct. NEVER EVER ignore warnings because most of the time they are really errors.

>>test1.c(39) : warning C4554: '&' : check operator precedence for possible error; use parentheses to clarify precedence

That warning message tells you to look at line 39 and check of the & operator is correct. Its not what you want -- you wanted the boolean && operator, not the bitwise & operator. The code has similar problem on other …

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

The link doesn't work and you didn't describe the problem with your code.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Yeeees! I didn't realize that was a link.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

No but you can go into your control panel and always see all of the reputation you've received

I can only see the first 15 reps. When I click on the arrow in the upper right corner of the rep box it blanks out the box and I see nothing, as if it had reached end-of-result-set in the database.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Depends on the compiler -- most c++ compilers will complain about that.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

line 21: you can delete it because the file pointer is already at the beginning of the file when it is opened.

line 26: you don't need the ios::in flag because ifstream is an input stream. All you need is infile.open( filename.c_str()); >>Is there a way to use an array to store the file handles?
Yes. One way to do it is like this:

ifstream* array = new ifstream[num];
...
 for(int i=0; i<num; i++) {
   std::stringstream num_str;
   num_str << i + 1;
   string filename = path + "/dir" + num_str.str() + "/" + file;

   array[i]->open(filename.c_str());

   if(!(array[i])) {
     cout << "opening " << filename << " failed" << endl;
     exit(1);
   }
   else {
     cout << filename << " opened" << endl;
   }
 }
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Another hint: check if an antivirus program is running on the computer. If it is, turn it off to see if that fixes the problem. I've seen Norton Antivirus have some problems with some valid programs. Turned off Norton and the problems went away. Of course you want to turn it back on before accessing the web.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

1) What kind of project did you create? console, win32 windows, something else?

2) what libraries did you try to link with?

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

First you have to declare a structure that is each node. If you search for "linked lists" you will get lots of examples, such as this tutorial by Stanford University.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

I've seen similar problems with Windows XP and earlier versions, and the only way I could resolve the problem was to reboot the computer. I'm using Vista Home now and have not had that problem with this version of Windows.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>>I wonder if it is possible to call the function void OneFunction()

Don't know myself. Instead of asking us if it is possible, why don't you just try to do it yourself? If you did, what were the results?

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

for real, man... me too!


by the way, have you met "TRIAD" ?

he's the original poster

:P

what do you mean? sorry.. my english isn't good, because it isn't my mother language..
but i'm trying to understand it..

Well Duuh! I didn't realize that was triadR, since it was in all caps I assumed it was an abbreviation that jephthah made up :)

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

TRIAD,
.

I hate it when people use acronyms that I don't know the meaning of.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

what if I did something like this:

int theFunction()
{
    //Bla blah blah, code here.
    //More code.
    int EndMarker;
    return 0;
}

would the address of EndMarker not be essentially the end of theFunction? Excluding the return, of course.

No -- the address of EndMarker is not even within the address space of the function. Its address is on the stack and the function code resides in the code segment(s).

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Since you did not mention it, I take it there is no way to do that?

I did mention it. If you want a YES or a NO, then the answer must be NO. If you think about it for a little while the sizeof is an operator, not a function, and is evaluated at compile time. And at compile time the final code for the target function hasn't even been generated. So how is the sizeof operator supposed to evaluate something that doesn't exist yet?

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

There is no portable way to do it because the number of bytes occupied by a function may vary by compiler and even within the same compiler from one compile to another. Most compilers will generate the assembly code for a program.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

how in the world did you think you can stuff that structure into a short int ? I'd like to wear a size 32 pants too but my fat butt won't fit into it.

Perform the checksum calculation on the individual members of the structure.

Nick Evan commented: haha, nice explanation +6
jephthah commented: lol +4
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

The extern keyword is used to tell the compiler that a data object is declared in a different *.cpp or *.c file (code unit). Its required for data objects but optional for function declarations. For example, you have two *.cpp files named A.cpp and B.cpp. B.cpp has a global int that needs to be used in A.cpp.

// A.cpp
#include <iostream>
// other includes here
...
extern int hours; // this is declared globally in B.cpp

int foo()
{
     hours = 1;
}
// B.cpp
#include <iostream>
// other includes here
...
int hours; // here we declare the object WITHOUT extern
extern void foo(); // extern is optional on this line

int main()
{
    foo();
}
Alex Edwards commented: Thank you for the clarification. It was never really explained in this way. +1
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

If you have a standard C or C++ program you can use the atexit() function

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Have you tried USB Central ?

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

I'm confused -- do you want the threads in RealBasic (whatever that is) or in the DLL? The code I posted will create the threads in the DLL and will work regardless of the language that calls it.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Check spelling and capitalization -- line 11 of the header file (as posted above) is not the same as the class name.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

The #ifdef directive is a PRECOMPILER directive that comments out or uncomments out a block of code depending on some other condition. This is performed before the code is even compiled, so the actual compiler never sees the #ifdef directive. Nor is it affected at program executation time.

The condition must be satisfied before compile time, not during runtime. So what you are attempting to do on line 15 is just not possible because those variables are not known until runtime.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>>When I'm opening a file, is it the file that is text or binary or is it the stream that can be text or binary?

Both. You can open any file in either text or binary mode. When you open a binary file in text mode your program will probably just read a whole lot of junk because the stream will mis-interpret the bytes in the file.

If you have a file that was written with the stream opened in binary file, try to load the file in a text editor such as Notepad. What you will see is a lot of unreadable characters, a lot of spaces, and/or a bunch of graphic squares.

>>when I close a file is that when the stream object is destroyed?
No. Like any other object that was created on the stack it is destroyed when the function returns

void foo()
{
   fstream fin; // create an object

   ...
   ...
   // last line of the function will destroy the fstream object
}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Yes you can use it, but I won't suggest it. Its a whole lot easier to use fread() and fwrite() to read/write to/from binary files.

// fgetc example
float f = 0;
unsigned char buf[sizeof(float)];
FILE* fp = fopen("myfile.dat", "rb");
// read a float
for(i = 0; i < sizeof(float); i++)
   buf[i] = fgetc(fp);
// move the contents of buf into the float variable
f = *(float *)buf;

Here is the same thing using fread

float f;
FILE* fp = fopen("myfile.dat", "rb");
// read the float
fread((char *)&f, sizeof(float),1,fp);

fread() is a lot less typing, lot less error prone, and more straight-forward.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

did you download the sdl source and compile it with your compiler?

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>>fatal error C1083: Cannot open include file: 'close_code.h': No such file or directory
It means exactuly what it says it means. The compiler can't find close_code.h ?

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

You didn't answer Niek's question. Which way do you expect to see the data ? If you want it similiar to what I posted then you can't use sprintf(). And the way I posted, one char can only hold a value up to 127 decimal (signed integer). If the values are larger than that then you can't do it my way.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Change the %x to %d with the sprintf()
use %c when printing the chars

this code:

works fine for me..

But I think he was expending a[0] to be 31.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

sprintf() doesn't work that way. Each digit of the number will be placed in a different element of the character array. So for 0x1f the a[0] == '1' and a[1] == 'f' (assuming "%x")

#include<stdio.h>
int main()
{
    char a[25] = {0};
	int i;
    a[0] = 0x1f;
    a[1] = 0x01;
    a[2] = 0x00271418;
	//sprintf(a,"%4d%4d%4d",0x0000001F,0x00000001,0x00271418);
	for(i=0; i <3; i++)
	{
		printf("%d\n",a[i]);
	}
    return 0;
}
}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

"%d" will produce decimal. If you want hex then use "%x"

Try this:

int main()
{
	char a[25];
	int i;
	sprintf(a,"%x%x%x",0x0000001F,0x00000001,0x00271418);
	for(i=0;i<8;i++)
	{
		printf("%c\n",a[i]);
	}
	return 0;
}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

Using VC++ 6.0 you can create a console program that supports MFC. This is what the VC++ 6.0 IDE creates in stdafx.h

// stdafx.h
#define VC_EXTRALEAN		// Exclude rarely-used stuff from Windows headers

#include <afx.h>
#include <afxwin.h>         // MFC core and standard components
#include <afxext.h>         // MFC extensions
#include <afxdtctl.h>		// MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h>			// MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT

#include <iostream>

And this is the *.cpp file it generates

/////////////////////////////////////////////////////////////////////////////
// The one and only application object
#include "stdafx.h"

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;

	// initialize MFC and print and error on failure
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
	{
		// TODO: change error code to suit your needs
		cerr << _T("Fatal Error: MFC initialization failed") << endl;
		nRetCode = 1;
	}
	else
	{
		// TODO: code your application's behavior here.
		CString strHello;
		strHello.LoadString(IDS_HELLO);
		cout << (LPCTSTR)strHello << endl;
	}

	return nRetCode;
}

Using the above program you can test for yourself whether it will support CWinThread or not.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>>when I try to #include afx.h so that I can build threads via AfxBeginThread I get the following error:

why are you including afx.h ? If you are using a Microsoft compiler and using precompiled headers then that is already included in stdafx.h

>>I was wondering if anyone could tell me how to interface with the MFC libraries in my console application?

Microsoft compilers can generate a console program that accesses SOME MFC (but not all). Console programs are limited to using only no-GUI related MFC classes, such as CString and CFile.

If you want to create threads in a console application use the win32 api function CreateThread().

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

You can not cast wchar_t* to char* because wchar_t data type is normally (but not always) a short int (2 bytes). On *nix machines wchar_t is a long int (4 bytes). Here is one way to make the conversion

do {
       char temp[_MAX_PATH]; // _MAX_PATH is defined as 255
       size_t nconv = 0;
       wcstombs_s(&nconv, temp,_MAX_PATH,ffd.cFileName, wcslen(ffd.cFileName)+1);
       //cout << ffd.cFileName << endl;
       cout << temp << "\n"; 
      cout << "Type = " << ( (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                             ? "dir\n" : "file\n" );
      cout << "Size = " << ffd.nFileSizeLow << "\n\n";
   } while (FindNextFile(sh, &ffd));
raul15791 commented: Knowledgeable +1
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>>Never see all that data types before
And you probably won't see them except in windows.h

Here is your program that works on my computer. I changed the path in main() for my computer, and deleted other extraneous/wrong code.

void EnumerateFolderFS(LPCTSTR path)
{
   WIN32_FIND_DATA ffd; // file information struct
   HANDLE sh = FindFirstFile(path, &ffd);
   if(INVALID_HANDLE_VALUE == sh) 
   {
	   return; // not a proper path i guess
   }

   
   // enumerate all items; NOTE: FindFirstFile has already got info for an item
   do {
      cout << ffd.cFileName << endl;
      cout << "Type = " << ( (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
                             ? "dir\n" : "file\n" );
      cout << "Size = " << ffd.nFileSizeLow << "\n\n";
   } while (FindNextFile(sh, &ffd));


   FindClose(sh);
}

int main()
{
	EnumerateFolderFS(_TEXT("D:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\include\\*.h"));

	cin.get();
	return 0;
}
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

stringstream (all one word) is a class that acts like fstream but instead of working with files it works with std::string.

line 24: delete that line. you are attempting to set a double to that of std::string, which is not possible. Re-read the code I posted vary carefully.

stringstream str(input);
str >> firstExam;

The above will convert the std::string into a double.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

>>EnumerateFolderFS(L"C:\\Documents and Settings\\skong3
Why are you forcing the string into wchar_t* wide characters? That's what the L does before the string.

Change that line like this and see how it works: EnumerateFolderFS(_TEXT("C:\\Documents and Settings\\skong3\\Desktop\\*.h");") The _TEXT is a macro that make the string either char* or wchar_t* depending on whether you compile your program for UNICODE or not.

Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster

You could use a std::string for input then convert to double if its not "N".

void compute()
{
	char firstExam;
                std::string input;
	double secondExam, thirdExam,avg;

	cout << "Enter the 1st test score (N to end): ";
	cin >> input; //firstExam;

	while (input != "N")
	{
                      stringstream str(input);
                      str >> firstExam;
		cout << "Enter the 2nd test score: ";
		cin >> secondExam;

		cout << "Enter the 3rd test score: ";
		cin >> thirdExam;


		avg = (firstExam + secondExam + thirdExam) / 3

		cout << avg << endl;

		cout << "Enter the 1st test score (N to end): ";
		cin >> firstExam;
	}
}