Clinton Portis 211 Practically a Posting Shark

I have seen an array struct in C that can hold data even if they are a different type.

This would be my best guess... but I'm open for suggestions:

void* array[4] = {5, 'Q', 2.7, 3.14159};

int* i = array;
char* c = array;
double* d = array;
float* f = array;

for(int i=0; i<4; i++)
{
     switch(i)
     {
          case 0:  cout << "Array as integer: ";
                       array = static_cast<int*>(array);
                       break;
          case 1:  cout << "Array as char: ";    
                       array = static_cast<char*>(array);
                       break;
          case 2:  cout << "Array as double: ";
                       array = static_cast<double*>(array);
                       break;
          case 3:  cout << "Array as float: ";    
                       array = static_cast<float*>(array);
                       break;
     }
     for(int j=0; j<4; j++)
 
          cout << array[j] << '\t';
 
     cout << endl;
}

void pointers
The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties).

This allows void pointers to point to any data type, from an integer value or a float to a string of characters. But in exchange they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it.

Clinton Portis 211 Practically a Posting Shark

Is there any specific piece of code you are looking at that is peaking your interest.. causing you to ask these questions? If so, please show us. It will help us to explain it to you if we actually have something to look at.

Clinton Portis 211 Practically a Posting Shark

The problem with your program is in it's design.

Here you throw everything inside of a huge loop... and yes, since you are testing eof() which is highly unrecommended, the loop will make at least 2 iterations:

ifstream myfile("BankData.txt");
     
     if (myfile.is_open())
     {                                            
          while (!myfile.eof())
          {                             
               myfile>>loginName;
               myfile>>password;
			
	       if(loginName == loginName1 && password == password1)
               {                  
                      menu();                  		
	       }				        
               else 
               {
                      cout<<"\tUnregistered ID or you have enter a wrong password !"<<endl;
           
                      cin.clear();
                      cin.ignore();
                      getchar();
                      return ;  
               }
			    
          myfile.close();
          }
    }

Not only that, you close() your ifstream obect, so on the 2nd iteration, your loop condition will fail.. causing your program to close.

Now, I will attempt to fix this mess:

if (!myfile.is_open())
     {            
          cout << "\a\nError! File did not open.";
          cout << "\nCheck if file exists, is in specified location, has been renamed, or deleted.";
          cout << "\nProgram will now terminate in preparation for file troubleshooting.";     
          cout << "\nPress [Enter] to exit program... ";
          cin.get();
          exit(EXIT_FAILURE);
     }                       
                                    
     myfile>>loginName;
     myfile>>password;
			
     if(loginName == loginName1 && password == password1)
     {                  
          menu();                  		
     }				        
               
     else 
     {
          cout << "\tUnregistered ID or you have enter a wrong password !" << endl;           
          cin.clear();
          cin.ignore();
          getchar();
          return;  
     }
			    
     myfile.close();

This is just one implemented solution of many possible. I know it's probably not exactly what you want. Feel free to tweak it as necessary to come up with your own solution.

Clinton Portis 211 Practically a Posting Shark

Just out of curiosity, I would like you to rebuild this code on your machine again with a call to GetTextMetrics().

We can then examine the last attribute of the TEXTMETRIC struct to determine the character set of the font.

if tmCharSet == 136 you are in Chinese.

Clinton Portis 211 Practically a Posting Shark

Your file contains one single line.

You are making at least 3 calls to getline()... and then making 2 extraction operations after that.

getline() will return a single line from your file.

your file only contains one line.

I would recommend either making one call to getline() (which will read the entire line at once) or make one extraction operation (since there are no white spaces in your line, it will in this case, also read the entire line at once.)

Once you have read in your single line, you can being parsing your line into individual pieces of data if you desire.

Clinton Portis 211 Practically a Posting Shark
#include<fstream>
#include<cstring>
#include<string>
#include<algorithm>

int line_counter = 0;
int word_counter = 0;
int punct_counter = 0;
int size = 0;
ifstream infile;
string line;

while(getline(infile, line))
{
     line_counter++;

     size = line.size();
     word_counter = count(&line[0], &line[size], ' ');
     word_counter++;

     for(int i=0; i<size; i++)
     {
          if(ispunct(line[i]))
          {
               punct_counter++;
          }
     }
}
Clinton Portis 211 Practically a Posting Shark

couple things:

You are using cstring library functions, without explicitly including the <cstring> header. If it works, hey that's fine. Just letting you know.

By putting your array counter at the beginning, you'll always skip over element[0]... I think this is why you are reading the same thing over and over whenever you try to access the first element of your arrays:

while(inFile)
	{
		count++;
		inFile >> lastName[count];
		inFile >> firstName[count];
		inFile >> phoneNumber[count];
		inFile >> email[count];
	}

I would put your counter at the end, so your first loop iteration will result in count equal to zero.

Clinton Portis 211 Practically a Posting Shark

I am impressed by your response. Everyone should take note of how you formed your original quesiton, implemented the solution, and how you explained your working knowlege of the solution.

You mentioned you tried to create your own 'string to cstring' function... although we both no that this is no longer necessary with the c_str() member, just for fun, I'll show you how I would have implemented it:

//String to Cstring
char* str_to_cstr(string& str, char* cstr)
{
     #include<cstring>

     int size = 0;
     char* temp = '\0';

     //Check cstring buffer to see if we have enough space available 
     if(strlen(cstr) < str.size())
     {
          //Resize the buffer to match string size
          temp = cstr;
          try{cstr = new char[str.size()+1];}
          catch(bad_alloc){return NULL;}       
          cstr = temp;
          delete temp;
     }

     //Now we can safely copy string to cstring
     strcpy(cstr, str.c_str());

     return cstr;
}

I need some more time to read it over... I don't quite get it understand by reading it. But thanks a lot for answering my question

To break it down really simple, the c_str() member allows the string object to be used as a cstring; therefore, giving it access to all <cstring> library functions.

So anytime you have a function (like open()) that accepts a char* (cstring or "or character array") you can still get all the benefits of using your string object, and still have the ability to pass it into these functions as a cstring... because c_str() returns a char* to a character array located as a private member …

Clinton Portis 211 Practically a Posting Shark

The block of code you just provided us appears that it would work as desired. Use of eof() is discouraged, but I don't see it as a major problem here.

You originally threw over 600 lines of code at us with a "Help me it doesn't work" type of request.

A better way to pose your question would be to tell us what part specifically doesn't work, what output you expect, and what output you are currently getting. Also, since this problem deals with file i/o, of course, we'll need to see a sample of your file.

Clinton Portis 211 Practically a Posting Shark

I would probably recommend the use of the curl library as way for your program to interface with the internet.

As far as multithreading goes.. it may be possible to open web pages on demand from the user as the user initiates the action; therefore, I would explore the possibility of event-driven launch of webpages before unnecessary multi-threading.

Clinton Portis 211 Practically a Posting Shark

test the attributes before issuing a cout instruction, if != 0 then display, else move on to the next attribute.

Clinton Portis 211 Practically a Posting Shark

In line #20 you declare a single object of type 'Employee'

In line #33 you attempt to dereferrence e using subscripts.. on your single 'Employee' object.

In lne #35 you again attempt to dereferrence your single e object using array subscripts.

You do not actually create an array of 'Employees' until line #48.

Clinton Portis 211 Practically a Posting Shark

How can I keep that from happening?

Fill them up with stuff.

Clinton Portis 211 Practically a Posting Shark

Since you are declaring 'p' locally from within the function, it will be destroyed with the function.. just as any locally declared function variable.

Additionally, you declare 'p' and it is never assigned anything. Later in your function you attempt to dereferrence a NULL pointer.

So the answer is, to declare a gobal variable named 'p' inside of int main() that you can pass into all your functions.

Clinton Portis 211 Practically a Posting Shark

can give some examples using my code above. I'll probably understand it more that way.

You will actually understand it less when you are spoon fed the code.

You seem like an intelligent individual.. why not give it a try? What's the worst that could happen..??

Isn't this an array? because of the

Being the astute CS student that I know you are, I'm sure you've studied the vector class and found out that it is based on the array datastructure:

Vector
Vectors are a kind of sequence containers. As such, their elements are ordered following a strict linear sequence.

Vector containers are implemented as dynamic arrays; Just as regular arrays, vector containers have their elements stored in contiguous storage locations, which means that their elements can be accessed not only using iterators but also using offsets on regular pointers to elements.

But unlike regular arrays, storage in vectors is handled automatically, allowing it to be expanded and contracted as needed.

Vectors are good at:

* Accessing individual elements by their position index (constant time).
* Iterating over the elements in any order (linear time).
* Add and remove elements from its end (constant amortized time).

So, to answer your question.. yes, the subscript operator is overloaded for the vector object, giving it array-like capability.

Clinton Portis 211 Practically a Posting Shark

can anyone help me convert this code from array to Vector?

I will help you.

  1. Instead of declaring an array, declare a vector.
  2. Anytime you want to add to the vector, call the push_back() member:
    myvector.push_back(input);
  3. Anytime you want to get stuff from the vector, you can use subscripts to access a specific array element:
    cout << myvector[i];
  4. You can get the size of the vector easily by calling the size() member:
    for(int i=0, size=myvector.size(); i<size; i++)
Clinton Portis 211 Practically a Posting Shark

//This is where I want to access p but don't know how.

The variable named 'p' does not exist anywhere within the scope of your Reposition() function.

Either pass it in from elsewhere or declare a local var named 'p'.. if this is what you desire.

So far, a variable named 'p' only exists as a local variable inside of the Search2() function.

Clinton Portis 211 Practically a Posting Shark

Could it be possible for me to read the file name as a string, and add the extension ".output" to the string, and then convert it back to an array of chars?

I'm glad you mentioned this. String class objects are very versitle and can handle virtually any input the user might throw at you.

If we look at the open() function from <fstream>, we see that it has a const char* (cstring) parameter as it's first argument.. which is the file name in a cstring:

fstream::open

public member function

void open ( const char * filename, ios_base::openmode mode = ios_base::in | ios_base::out );

But we are using a string.. what are we supposed to do? Luckily, there is a <string> class member function called c_str() which returns a cstring pointer:

const char* c_str ( ) const;

Get C string equivalent
Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.

A terminating null character is automatically appended.

Knowing all this, we can take all user input in the form of a string, concantinate the string with the required file identifier (.txt) and pass the string into the open() function by calling the c_str() member:

#include<string>

string name;

cout << "Enter file name: ";
cin >> name;

//Check to see if user already appended the file type
if(name.find(".txt") == string::npos)
{
    //If user did not add file …
Darkmist commented: The example on c_str() was really clear and easy to understand +0
Clinton Portis 211 Practically a Posting Shark

You have ye'self a good workin' program up there.. just had to make 2 minor changes:

//this
coin = 1 +rand()%2;
//should be this:
coin = 1 +rand()%3;

//this
int money = head - tail;
//should be this:
int money = won - tail;
Clinton Portis 211 Practically a Posting Shark

My bad.. i told you I was in a rush to save my noodles. Would have liked to have seen more effort on your part with simple debugging:

for(int loopcounter=0; loopcounter<5; loopcounter++)
{
    switch(loopcounter)
    {
         case 0:  cout << "Grade A: |"; break;
         case 1:  cout << "Grade B: |"; break;
         case 2:  cout << "Grade C: |"; break;
         case 3:  cout << "Grade D: |"; break;
         case 4:  cout << "Grade F: |"; break;
    }

    //loop to output each asterisk
    for(int asteriskcounter=0; asteriskcounter<array[loopcounter]/2; asteriskcounter++)
    {
        cout << '*';
    }

    cout << "| " << array[loopcounter] << '%'<< endl;
}
Clinton Portis 211 Practically a Posting Shark

I'll make a deal with you.. put code tags around your code, and I will solve your problem for you.

I'll even take out the math.. which is the most complex I have seen for a coin flippin' game.

Clinton Portis 211 Practically a Posting Shark

Obviously, the only solution is to learn Chinese.

or show us your code.

Clinton Portis 211 Practically a Posting Shark

I just made this up because I am currently cooking macaroni and cheese, and I think my noodles are being overcooked as we speak.

However, give this a try. If the output is not what you desire, feel free to tweak it as necessary before asking how to improve it:

for(int loopcounter=0; loopcounter<6; loopcounter++)
{
    switch(loopcounter)
    {
         case 0:  cout << "\nGrade A: |"; break;
         case 1:  cout << "\nGrade B: |"; break;
         case 3:  cout << "\nGrade C: |"; break;
         case 4:  cout << "\nGrade D: |"; break;
         case 5:  cout << "\nGrade F: |"; break;
    }    
    
    //loop to output each asterisk
    for(int asteriskcounter=0; asteriskcounter<array[loopcounter]/2; asteriskcounter++)
    {
        cout << '*';
    }  
    
    cout << "| " << array[loopcounter] << '%';
}
Clinton Portis 211 Practically a Posting Shark

After assigning a player move to the game_grid[][], in order to display the newly updated board, just use a nested loop to walk through your array, displaying all elements to the screen:

void display(int board[][])
{
     //Display all  contents of the array
     for(int i=0; i<3; i++)
          for(int j=0; j<3; j++)

               cout << board[i][j];
}
Clinton Portis 211 Practically a Posting Shark

That is an excellent question, and I will break it down for you:

  1. Start at the top of your code
  2. Begin reading through your code
  3. Anytime you see 'int', replace with 'double'
  4. Continue the previous step until you have reached end of code

Compile, run and enjoy.

Clinton Portis 211 Practically a Posting Shark
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
  string mystr;
  double price=0;
  double pay = 0;
  int quantity=0;
  

  cout << "Enter price: ";
  getline (cin,mystr);
  stringstream(mystr) >> price;
  cout << "Enter quantity: ";
  getline (cin,mystr);
  stringstream(mystr) >> quantity;
  cout << "Total price: " << price*quantity << endl;

  cout << "Pay: ";
  getline (cin,mystr);
  stringstream(mystr) >> pay;
  cout << "Change: " << pay - price*quantity << endl;

  return 0;
}
Clinton Portis 211 Practically a Posting Shark

I was all for integer division, and I believe it would have worked in that it would just truncate any decimal value to a whole integer.

But I guess this was not the case this time.

Change all your int's to doubles (or floats.. remember to set your precision) and I think you'll be happy with the results.

Clinton Portis 211 Practically a Posting Shark

i have here a standard visual c++ function that clears the screen

Be rest assured, this is not standard c++.

What this is though, is a group of functions derived from <windows.h> called the "windows advanced programming interface" or API.

The window.h library contains thousands of functions that allow you access to the deep internal workings of your computer. With the windows api, you can create windows, draw bitmaps, create multi-threaded programs, play sound, create timers, send data to the printer, create makefiles, and edit the system registry... and that just for starters. As you can see, it is a very powerful api.

Although very powerful, it is also very non-portable and is specific to only windows operating systems.

The forger's win32 tutorial is where most people go to get their first glimpse of windows programming.

More relevant to your question, here is a cool tutorial for windows programming in the dos environment.

So, to answer your question, we'll go through each function and tell briefly what it does:

GetStdHandle()

Returns a 'Handle' to the Dos Console window.

GetConsoleScreenBufferInfo()
The sole purpose of this function is to populate a struct called, CONSOLE_SCREEN_BUFFER_INFO with useful information.

Here is the groovy information that can be found inside the CONSOLE_SCREEN_BUFFER_INFO struct:

typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
  COORD      dwSize;
  COORD      dwCursorPosition;
  WORD       wAttributes;
  SMALL_RECT srWindow;
  COORD      dwMaximumWindowSize;
} CONSOLE_SCREEN_BUFFER_INFO

COORD …

Clinton Portis 211 Practically a Posting Shark
vector<MyClass> MyVector;
MyVector.push_back(MyClass(Param1, Param2, Parm3, Param4));

As I understand this would involve creating two instances of the object and copying one to the other. Is that correct?

As I see it, you are creating one instance of 'myclass' which pushed into the vector.

Would it run quicker if I change the vector to pointers like this:

vector<MyClass*> MyVector;
MyVector.push_back(new MyClass(Param1, Param2, Parm3, Param4));

One downfall I see to this method, based on the sheer number of calls to allocate new memory, you should at least be prepared to handle a bad_alloc exception. This method also involves some time for the OS to find an allocate memory for each 'new' operation.

If you want to boost your performance, try taking control of the vector memory allocation using member functions such as: max_size(), capacity(), reserve(), and resize().

Clinton Portis 211 Practically a Posting Shark

I am doing my best to imagine your current code...

I was wondering if you could help me out by posting what you have thus far.. if you don't mind.

Clinton Portis 211 Practically a Posting Shark

You are probably displaying too many asterisks.

Each asterisk is supposed to represent 2% as per assignment requirement.

As of now, each asterisk represents 1%.

Therefore, you will have to reduce your asterisk output by 1/2:

for(int asteriskcounter=0; asteriskcounter<array[loopcounter]/2; asteriskcounter++)
Clinton Portis 211 Practically a Posting Shark

Are you kidding me?

cout<<"Please enter how many grade E's"<<endl;
cin>>e;

Use basic math to calculate a percentage for each letter grade:

Acent = a / total * 100;
Bcent = b / total * 100;
Ccent = c / total * 100;
Dcent = d / total * 100;
Fcent = f / total * 100;

This will give you the overall average grade:

average = (Acent+Bcent+Ccent+Dcent+Fcent) / total;
Clinton Portis 211 Practically a Posting Shark

I wish you luck on your endeavors.

Clinton Portis 211 Practically a Posting Shark

I'm very new to C#

Do you think asking for homework help in a c++ forum will further your efforts in learning c pound?

  1. Accept input from user.
  2. Store input from user in a container of your choice (probably an int array)
  3. Using a loop, step through the array
  4. At each element of the array, use another loop to display the correct number of asterisks

You seem like an intelligent individual.. give this a try. We'd love to see your code.

Clinton Portis 211 Practically a Posting Shark

Try this:

class racunalo
{
     private:

          struct komp
          {
               string naziv;
               string velicinaRam;
               string velicinaHDD;
               string brzina;
               string proizvodac;
         };

          vector<komp> racunala;         

     public:

          komp get_komp(int index){return racunala[index];}
          vector<komp> get_rac(){return racunala;}
          void erase(int element){racunala.erase(racuanala.begin()+element);}
          void erase(int first, int last){racunala.erase(racunala.begin()+first, racunala.begin()+last);}
};

int main()
{
     racunalo rac;
 
     for(int i=0; i<br; i++)
     {
          if(rac.get_komp(i).naziv == comp_name)
          {
               rac.erase(i);
               br--;
               i--;
          }
     }
     return 0;
}
Clinton Portis 211 Practically a Posting Shark

You need access to the vector as it is a private member of class racunalo.

getNaziv() does not do this for you, as it returns a 'string'

few possible options:

  • make racunala public.
  • create an accessor function that will return a pointer to racunala.
  • declare a public iterator to racunala.
  • create an accessor function that will return a private iterator
  • declare the struct and vector outside the scope of the class.
Clinton Portis 211 Practically a Posting Shark

Why are you trying to access a second element, in a 1 element vector?


Unless I am missing something..

//I think this...
if(kompjuteri.getNaziv(i) == comp_name){
     racunala.erase(racunala.begin()+i);}

//Should be this:
if(racunala[i].naziv == comp_name){
     racunala.erase(racunala.begin()+i);}
Clinton Portis 211 Practically a Posting Shark
Clinton Portis 211 Practically a Posting Shark

Steps #1 through #9 are complete. Aside from the required error handling, the bulk of your project is complete.

Perhaps we could come up with a couple of functions to test user input for validity. If invalid, throw an error; catch error and respond appropriately.

But since I am tired as heck, I am about do like my programs and crash.

Nick Evan commented: You derserve rep for this monster thread. +11
jonsca commented: nuff said +1
Clinton Portis 211 Practically a Posting Shark

Yes... I think that works as long as there are no cin >> operations that take place between the ignore() and the getline() operation.

I believe the cin operation will leave an extraneous newline character in the input buffer that will thwart the efforts of getline() to read the buffer.

It's 2:00am... what am I doing here...

Clinton Portis 211 Practically a Posting Shark

You are a college student. This is not a proper and/or complete sentence:

it is isnt it getline is at 90 and the other is at 87

I will allow you one more opportunity to form a comprehensible question that resembles the English language.

Clinton Portis 211 Practically a Posting Shark

I don't know what you are talking about in your previous 3 posts. They seem to be random thoughts. Perhaps you are experiencing dementia associated with hours of coding in c++.

Clinton Portis 211 Practically a Posting Shark

If it meets your project requirements and your compiler likes it, then it is declared right.

Also, try putting line #87 right before you call getline() at line #90.

Clinton Portis 211 Practically a Posting Shark

i called the function in line 18

You did not call the function in line#18, you simply declared the function prototype.

You called the function at line#41.

Clinton Portis 211 Practically a Posting Shark

Here is what I came up with for step #9.. maybe you came up with something better:

void PrintStudents(Student array[], int size)
{
    for(int i=0; i<size; i++)
    {
         cout << array[i].Name << ' ' << array[i].GPA << ' ' << array[i].Major << endl;
    }
}
Clinton Portis 211 Practically a Posting Shark

i am not understanding this program isnt it suppose to do something with the numbers

It does nothing but record user input into different c++ data types, and then return the same user input back to the dos console.

Think of it as a database (or record keeping) program.

Clinton Portis 211 Practically a Posting Shark

i did but in your code you took out the & sign from those locations

Then I would suggest that you make your code look like my code.

Clinton Portis 211 Practically a Posting Shark

if i do that it tells me its an unused variable

Yes, the Students[] array is declared, and not used.. that is until you complete step #8:

8. Call the function GetStudents from main.

Now the variable will be used and your compiler will stop issuing you those warnings.

its because of the &

Just take away the address operator (since we are passing in a constant)

Clinton Portis 211 Practically a Posting Shark

and what did the getstudent really do when i run it i seen nothing changing

Does your code look anything like this? If not, then maybe you should make the proper adjustments:

#include<iostream>
using namespace std;


struct Student
{
     char Name[30];
     float GPA;
     int Major;
};

//Function prototypes
Student* StudentData(Student* S);
void display(Student* S);
void ChangeData(Student* S);
void GetStudents(Student array[], int size);


//main driver
int main()
{
     //Declare two objects of type 'Student'; step #1
     Student* S1 = new Student;
     Student* S2 = new Student;
     //Step #6 requirement
     Student Students[2];

     //Pass this object into our function so it can be filled up with useful information; step #2
     S1 = StudentData(S2);
     //Display new and exciting information to the DOS console; step #3
     display(S1);
     display(S2);
     //Function call to change data in S2 as per step #4 requirement
     ChangeData(S2);
     //Function call to dsiplay the newly changed S2 object as per step #5
     display(S2);
     //Step #7
     GetStudents(Students, 2);

return 0;
}


//Function Definitions
Student* StudentData(Student* S)
{
     cout << "Enter name: ";
     cin >> S->Name;

     cout << "Enter GPA: ";
     cin >> S->GPA;

     cout << "Enter major: " ;
     cin >> S->Major;

     return S;
}

void display(Student* S)
{
    cout << S->Name  << endl;
    cout << S->GPA   << endl;
    cout << S->Major << endl;
}

void ChangeData(Student* S)
{
     cout << "Enter name: ";
     cin >> S->Name;

     cout << "Enter GPA: ";
     cin >> S->GPA;

     cout << "please enter major: " ;
     cin >> S->Major;
}

void GetStudents(Student array[], int size)
{
     for(int …
Clinton Portis 211 Practically a Posting Shark

put it with the rest of your variable declarations:

//Declare two objects of type 'Student' as wanted in step #1
Student* S1 = new Student;
Student* S2 = new Student;
Student Students[2];

Your future employer will love you.