char* string?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jordan Tiona

    char* string?

    How can I make one of these? I'm trying to get my program to store a string
    into a variable, but it only stores one line.

    --
    "No eye has seen, no ear has heard, no mind can
    conceive what God has prepared for those who love him"
    1 Cor 2:9


  • mlimber

    #2
    Re: char* string?

    Jordan Tiona wrote:[color=blue]
    > How can I make one of these? I'm trying to get my program to store a string
    > into a variable, but it only stores one line.[/color]

    Please elaborate (preferably with source code; cf.
    http://parashift.com/c++-faq-lite/ho....html#faq-5.8). You should
    prefer std::string to char* strings anyway.

    Cheers! --M

    Comment

    • Jordan Tiona

      #3
      Re: char* string?

      "mlimber" <mlimber@gmail. com> wrote in message
      news:1145373387 .831126.199900@ e56g2000cwe.goo glegroups.com.. .[color=blue]
      > Jordan Tiona wrote:[color=green]
      >> How can I make one of these? I'm trying to get my program to store a
      >> string
      >> into a variable, but it only stores one line.[/color]
      >
      > Please elaborate (preferably with source code; cf.
      > http://parashift.com/c++-faq-lite/ho....html#faq-5.8). You should
      > prefer std::string to char* strings anyway.
      >
      > Cheers! --M
      >[/color]

      Sorry. I've decided to go with std::string. However, how do I print one of
      these? If I have a string called "tempStr", and have this statement: "cout
      << tempStr", I get an error.


      Comment

      • Rolf Magnus

        #4
        Re: char* string?

        Jordan Tiona wrote:
        [color=blue]
        > "mlimber" <mlimber@gmail. com> wrote in message
        > news:1145373387 .831126.199900@ e56g2000cwe.goo glegroups.com.. .[color=green]
        >> Jordan Tiona wrote:[color=darkred]
        >>> How can I make one of these? I'm trying to get my program to store a
        >>> string
        >>> into a variable, but it only stores one line.[/color]
        >>
        >> Please elaborate (preferably with source code; cf.
        >> http://parashift.com/c++-faq-lite/ho....html#faq-5.8). You should
        >> prefer std::string to char* strings anyway.
        >>
        >> Cheers! --M
        >>[/color]
        >
        > Sorry. I've decided to go with std::string. However, how do I print one of
        > these? If I have a string called "tempStr", and have this statement: "cout
        > << tempStr", I get an error.[/color]

        Do you really think that's an adequate description of your problem? Show us
        a minimal, but complete program that has the observed error, as well as the
        exact error message you got from the compiler. I'm not really in the mood
        of solving riddles today.

        Comment

        • mlimber

          #5
          Re: char* string?

          Jordan Tiona wrote:[color=blue]
          > Sorry. I've decided to go with std::string. However, how do I print one of
          > these? If I have a string called "tempStr", and have this statement: "cout
          > << tempStr", I get an error.[/color]

          You shouldn't (unless your statement is also missing the semicolon).
          Show us the offending code (cf. the FAQ mentioned above).

          Cheers! --M

          Comment

          • Guest's Avatar

            #6
            Re: char* string?


            "Jordan Tiona" <torahteen@comc ast.net> wrote in message
            news:Fe6dnd3OT-eKltjZRVn-uQ@comcast.com. ..
            | "mlimber" <mlimber@gmail. com> wrote in message
            | news:1145373387 .831126.199900@ e56g2000cwe.goo glegroups.com.. .
            | > Jordan Tiona wrote:
            | >> How can I make one of these? I'm trying to get my program to store a
            | >> string
            | >> into a variable, but it only stores one line.
            | >
            | > Please elaborate (preferably with source code; cf.
            | > http://parashift.com/c++-faq-lite/ho....html#faq-5.8). You should
            | > prefer std::string to char* strings anyway.
            | >
            | > Cheers! --M
            | >
            |
            | Sorry. I've decided to go with std::string. However, how do I print one of
            | these? If I have a string called "tempStr", and have this statement: "cout
            | << tempStr", I get an error.
            I have tried "cout << tempStr" and it works for me. Anyway you can try
            "cout << tempStr.c_str() " intead.


            Comment

            • Jordan Tiona

              #7
              Re: char* string?

              "mlimber" <mlimber@gmail. com> wrote in message
              news:1145375732 .589800.199270@ t31g2000cwb.goo glegroups.com.. .[color=blue]
              > Jordan Tiona wrote:[color=green]
              >> Sorry. I've decided to go with std::string. However, how do I print one
              >> of
              >> these? If I have a string called "tempStr", and have this statement:
              >> "cout
              >> << tempStr", I get an error.[/color]
              >
              > You shouldn't (unless your statement is also missing the semicolon).
              > Show us the offending code (cf. the FAQ mentioned above).
              >
              > Cheers! --M
              >[/color]

              I'm sorry again. I didn't think that code was truly required to answer this
              question. Here is my code, without strings. It is kind of long, I apologize.
              (BTW, this IS homework, but you helping me with problems like this shouldn't
              be a problem right?)

              W7Graded.cpp

              /*------------------------------------------------------/*
              /* Workshop 7 -- Graded Project /*
              /* Jordan Tiona /*
              /* Last Updated April 17, 2006 /*
              /*------------------------------------------------------*/

              //Included Files

              #include <iostream>
              #include <stdio.h>
              #include "W7Graded.h "
              using namespace std;

              //Function Prototypes

              void PrintData();
              void EnterData();
              void SaveData();
              void LoadData();

              //Global Variables

              cdData* cd; //Linked List

              int main(){
              cd = new cdData();
              int choice;
              bool quit = false;
              while(quit == false){
              system("cls");
              cout << "Welcome to CD Tracker \n\n";

              cout << "What would you like to do?\n";
              cout << "\t(1)Print Current Data\n";
              cout << "\t(2)Enter New Data\n";
              cout << "\t(3)Save Current Data\n";
              cout << "\t(4)Load Data\n";
              cout << "\t(5)Exit\ n";
              cin >> choice;

              switch(choice){
              case 1: PrintData();
              break;
              case 2: EnterData();
              break;
              case 3: SaveData();
              break;
              case 4: LoadData();
              break;
              case 5: quit = true;
              break;
              default: cout << "\n Invalid choice. Please try again\n";
              }
              }
              return 1;
              }

              void PrintData(){

              cdData* curNode = cd;
              char* tempStr;
              int tempInt;

              system("cls");
              do{
              tempStr = curNode->GetName();
              if(tempStr != NULL)
              cout << "CD Name: " << *tempStr << endl;
              cout << "-------------------------------------\n";
              tempStr = curNode->GetArtist();
              if(tempStr != NULL)
              cout << "Artist: " << *tempStr << endl;
              tempInt = curNode->GetYear();
              cout << "Year Released: " << tempInt << endl;

              curNode = curNode->GetNext();
              }while(curNode != NULL);
              system("pause") ;
              }

              void EnterData(){

              bool stop = false;
              char *tempStr;
              int tempInt;
              cdData* curNode = cd;
              char yn;

              tempStr = new char();

              //Get to the end of the linked list first
              while(curNode->GetNext() != NULL){ //If there isn't anything after this
              node, then this is the end of the list
              curNode = curNode->GetNext(); //Go to the next Node
              }

              while(stop == false){
              system("cls");
              cin.ignore();
              //Add a new node
              curNode->SetNext(new cdData());
              curNode = curNode->GetNext();

              cout <<"\nName of CD: ";
              cin.getline(tem pStr, MAX_LENGTH);
              curNode->SetName(tempSt r);

              tempStr = new char();

              cout <<"\n\nName of Artist: ";
              cin.getline(tem pStr, MAX_LENGTH);
              curNode->SetArtist(temp Str);

              cout <<"\n\nYear Released: ";
              cin >> tempInt;
              curNode->SetYear(tempIn t);

              system("cls");
              cout <<"Enter another CD? (Y/N)\n";
              cin >> yn;

              if(yn == 'Y' || yn == 'y')
              stop = false;
              else
              stop = true;
              }

              }

              void SaveData(){
              }

              void LoadData(){
              }

              W7Graded.h

              //CD Data
              const int MAX_LENGTH = 21;

              class cdData {
              private:
              //CD Data
              char* cdName;
              char* artist;
              int year;
              //Linked List Data
              cdData* next;
              public:
              //Constructor/Destructor
              cdData(){next = NULL;
              artist = NULL;
              cdName = NULL;}
              ~cdData(){}
              //Accessors
              char* GetName(){retur n cdName;}
              char* GetArtist(){ret urn artist;}
              int GetYear(){retur n year;}

              void SetName(char* newName){cdName = newName;}
              void SetArtist(char* newName){artist = newName;}
              void SetYear(int newYear){year = newYear;}

              cdData* GetNext(){retur n next;}
              void SetNext(cdData* newNext){next = newNext;}
              };

              I can't put more than one character in the "cdName" variable. How do I get
              more than one character (or more than one word for that matter)?


              Comment

              • Gavin Deane

                #8
                Re: char* string?


                Jordan Tiona wrote:[color=blue]
                > "mlimber" <mlimber@gmail. com> wrote in message
                > news:1145375732 .589800.199270@ t31g2000cwb.goo glegroups.com.. .[color=green]
                > > Jordan Tiona wrote:[color=darkred]
                > >> Sorry. I've decided to go with std::string. However, how do I print one
                > >> of
                > >> these? If I have a string called "tempStr", and have this statement:
                > >> "cout
                > >> << tempStr", I get an error.[/color]
                > >
                > > You shouldn't (unless your statement is also missing the semicolon).
                > > Show us the offending code (cf. the FAQ mentioned above).
                > >
                > > Cheers! --M
                > >[/color]
                >
                > I'm sorry again. I didn't think that code was truly required to answer this
                > question. Here is my code, without strings. It is kind of long, I apologize.
                > (BTW, this IS homework, but you helping me with problems like this shouldn't
                > be a problem right?)[/color]

                Please review


                Your code is neither minimal nor compilable. Compilable means that I
                can copy and paste from your message directly into my editor and
                compile it. If your question is about compile errors, I will see those
                errors. If your question is about behaviour of the program, I will be
                able to build the program and run it to see the behaviour. With the
                code you posted, I can do neither. I just get an error about not being
                able to find "W7Graded.h ". Not surprising since I don't have it on my
                computer.

                But before you go ahead and follow the advice in point 4 in that FAQ,
                think about minimal. Minimal means the *smallest possible* program you
                can create that exhibits your problem. Take what you've got at the
                moment and start stripping bits out, one at a time. Each time you
                remove something, recompile and see if you get the same error. When the
                error goes away, whatever you removed last was causing the problem.
                Often, during this process, you will find the problem yourself anyway.

                And finally, if you don't manage to fix it yourself by stripping the
                code down, please make it clear what your question is. See point 7 in
                that FAQ. In a previous message you said you had switched from char* to
                std::string, but were having trouble printing one with cout. When asked
                for code, you posted a far from minimal example without a single
                std::string in it. Instead, you asked how to fit more than one
                character into a char*. The answer to that is that you should prefer
                std::string. But we've already been there. Can you see how it's quite
                difficult to help you?

                Gavin Deane

                Comment

                • Andre Kostur

                  #9
                  Re: char* string?

                  Jordan Tiona wrote:[color=blue]
                  > "mlimber" <mlimber@gmail. com> wrote in message
                  > news:1145375732 .589800.199270@ t31g2000cwb.goo glegroups.com.. .[color=green]
                  >> Jordan Tiona wrote:[color=darkred]
                  >>> Sorry. I've decided to go with std::string. However, how do I print one
                  >>> of
                  >>> these? If I have a string called "tempStr", and have this statement:
                  >>> "cout
                  >>> << tempStr", I get an error.[/color]
                  >> You shouldn't (unless your statement is also missing the semicolon).
                  >> Show us the offending code (cf. the FAQ mentioned above).
                  >>
                  >> Cheers! --M
                  >>[/color]
                  >
                  > I'm sorry again. I didn't think that code was truly required to answer this
                  > question. Here is my code, without strings. It is kind of long, I apologize.
                  > (BTW, this IS homework, but you helping me with problems like this shouldn't
                  > be a problem right?)[/color]

                  Specific C++ questions generally aren't an issue. It's when people come
                  in an expect us to basically write their entire homework assignment,
                  then we get ornery.

                  Having said that, you just said that you've "decided to get with
                  std::string", but I don't see a std::string _anywhere_ in this code...
                  [color=blue]
                  > W7Graded.cpp
                  >
                  > /*------------------------------------------------------/*
                  > /* Workshop 7 -- Graded Project /*
                  > /* Jordan Tiona /*
                  > /* Last Updated April 17, 2006 /*
                  > /*------------------------------------------------------*/
                  >
                  > //Included Files
                  >
                  > #include <iostream>
                  > #include <stdio.h>
                  > #include "W7Graded.h "
                  > using namespace std;
                  >
                  > //Function Prototypes
                  >
                  > void PrintData();
                  > void EnterData();
                  > void SaveData();
                  > void LoadData();
                  >
                  > //Global Variables
                  >
                  > cdData* cd; //Linked List
                  >
                  > int main(){
                  > cd = new cdData();
                  > int choice;
                  > bool quit = false;
                  > while(quit == false){
                  > system("cls");
                  > cout << "Welcome to CD Tracker \n\n";
                  >
                  > cout << "What would you like to do?\n";
                  > cout << "\t(1)Print Current Data\n";
                  > cout << "\t(2)Enter New Data\n";
                  > cout << "\t(3)Save Current Data\n";
                  > cout << "\t(4)Load Data\n";
                  > cout << "\t(5)Exit\ n";
                  > cin >> choice;[/color]

                  Warning... see what happens if a user doesn't enter a numeric value....
                  [color=blue]
                  > switch(choice){
                  > case 1: PrintData();
                  > break;
                  > case 2: EnterData();
                  > break;
                  > case 3: SaveData();
                  > break;
                  > case 4: LoadData();
                  > break;
                  > case 5: quit = true;
                  > break;
                  > default: cout << "\n Invalid choice. Please try again\n";
                  > }
                  > }
                  > return 1;
                  > }
                  >
                  > void PrintData(){
                  >
                  > cdData* curNode = cd;
                  > char* tempStr;
                  > int tempInt;
                  >
                  > system("cls");
                  > do{
                  > tempStr = curNode->GetName();
                  > if(tempStr != NULL)
                  > cout << "CD Name: " << *tempStr << endl;[/color]

                  *tempStr is a character. You probably don't want to dereference tempStr
                  here. (at least it appears that you're using it in the context of a
                  C-style string...)
                  [color=blue]
                  > cout << "-------------------------------------\n";
                  > tempStr = curNode->GetArtist();
                  > if(tempStr != NULL)
                  > cout << "Artist: " << *tempStr << endl;[/color]

                  Same as above.
                  [color=blue]
                  > tempInt = curNode->GetYear();
                  > cout << "Year Released: " << tempInt << endl;
                  >
                  > curNode = curNode->GetNext();
                  > }while(curNode != NULL);
                  > system("pause") ;
                  > }
                  >
                  > void EnterData(){
                  >
                  > bool stop = false;
                  > char *tempStr;
                  > int tempInt;
                  > cdData* curNode = cd;
                  > char yn;
                  >
                  > tempStr = new char();[/color]

                  tempStr is now pointing at enough memory to hold 1 char.... (Looking a
                  little further forward, are you sure you don't want:

                  tempStr = new char[MAX_LENGTH + 1];

                  ? That is a "string" long enough to hold MAX_LENGTH, plus 1 character
                  for the terminating 0-char (that is the char with the value 0, not the
                  '0' character).
                  [color=blue]
                  > //Get to the end of the linked list first
                  > while(curNode->GetNext() != NULL){ //If there isn't anything after this
                  > node, then this is the end of the list
                  > curNode = curNode->GetNext(); //Go to the next Node
                  > }
                  >
                  > while(stop == false){
                  > system("cls");
                  > cin.ignore();
                  > //Add a new node
                  > curNode->SetNext(new cdData());
                  > curNode = curNode->GetNext();
                  >
                  > cout <<"\nName of CD: ";
                  > cin.getline(tem pStr, MAX_LENGTH);[/color]

                  Under your original code, this results in a "buffer overflow", and is
                  likely to crash your program (but not guaranteed... this is what's
                  called Undefined Behaviour).
                  [color=blue]
                  > curNode->SetName(tempSt r);
                  >
                  > tempStr = new char();[/color]

                  See above.
                  [color=blue]
                  > cout <<"\n\nName of Artist: ";
                  > cin.getline(tem pStr, MAX_LENGTH);[/color]

                  See above.
                  [color=blue]
                  > curNode->SetArtist(temp Str);
                  >
                  > cout <<"\n\nYear Released: ";
                  > cin >> tempInt;
                  > curNode->SetYear(tempIn t);
                  >
                  > system("cls");
                  > cout <<"Enter another CD? (Y/N)\n";
                  > cin >> yn;
                  >
                  > if(yn == 'Y' || yn == 'y')
                  > stop = false;
                  > else
                  > stop = true;
                  > }
                  >
                  > }
                  >
                  > void SaveData(){
                  > }
                  >
                  > void LoadData(){
                  > }
                  >
                  > W7Graded.h
                  >
                  > //CD Data
                  > const int MAX_LENGTH = 21;
                  >
                  > class cdData {
                  > private:
                  > //CD Data
                  > char* cdName;
                  > char* artist;
                  > int year;
                  > //Linked List Data
                  > cdData* next;
                  > public:
                  > //Constructor/Destructor
                  > cdData(){next = NULL;
                  > artist = NULL;
                  > cdName = NULL;}[/color]

                  Prefer initialization lists to initialization within the body. That is,
                  write this instead:

                  cdData() : next(NULL), artist(NULL), cdName(NULL) {};

                  The advantage here (which doesn't mean much for a simple pointer, but
                  more of an issue with more complex classes) is that in your form, the
                  variables next, artist and cdName need to the default-initialized first,
                  then assigned a value. With an initialization list, the variables would
                  be constructed with the right values to begin with.
                  [color=blue]
                  > ~cdData(){}
                  > //Accessors
                  > char* GetName(){retur n cdName;}
                  > char* GetArtist(){ret urn artist;}
                  > int GetYear(){retur n year;}
                  >
                  > void SetName(char* newName){cdName = newName;}
                  > void SetArtist(char* newName){artist = newName;}
                  > void SetYear(int newYear){year = newYear;}
                  >
                  > cdData* GetNext(){retur n next;}
                  > void SetNext(cdData* newNext){next = newNext;}
                  > };
                  >
                  > I can't put more than one character in the "cdName" variable. How do I get
                  > more than one character (or more than one word for that matter)?[/color]

                  Other items to note:

                  1) Your program leaks memory like a sieve. I see many instances of "new
                  char" (which probably should be "new char[MAX_LENGTH + 1]"), but I
                  don't ever see a call to "delete" (or delete[] if you fix the allocations).
                  2) This gets a whole lot easier if you change to std::strings. All of
                  the dynamic memory stuff related to "strings" goes away.
                  3) If you're trying to read an entire line into a std::string, look up
                  std::getline() (and not the getline() that is a member of a stream).
                  4) I'm assuming it's part of the assignment that you can't use the rest
                  of the standard C++ library (like std::list, or some other container)?

                  Comment

                  • Jordan Tiona

                    #10
                    Re: char* string?

                    "Andre Kostur" <nntpspam@kostu r.net> wrote in message
                    news:NV81g.1246 $DR6.95983@news 20.bellglobal.c om...[color=blue]
                    > Jordan Tiona wrote:[color=green]
                    >> "mlimber" <mlimber@gmail. com> wrote in message
                    >> news:1145375732 .589800.199270@ t31g2000cwb.goo glegroups.com.. .[color=darkred]
                    >>> Jordan Tiona wrote:
                    >>>> Sorry. I've decided to go with std::string. However, how do I print one
                    >>>> of
                    >>>> these? If I have a string called "tempStr", and have this statement:
                    >>>> "cout
                    >>>> << tempStr", I get an error.
                    >>> You shouldn't (unless your statement is also missing the semicolon).
                    >>> Show us the offending code (cf. the FAQ mentioned above).
                    >>>
                    >>> Cheers! --M
                    >>>[/color]
                    >>
                    >> I'm sorry again. I didn't think that code was truly required to answer
                    >> this question. Here is my code, without strings. It is kind of long, I
                    >> apologize. (BTW, this IS homework, but you helping me with problems like
                    >> this shouldn't be a problem right?)[/color]
                    >
                    > Specific C++ questions generally aren't an issue. It's when people come
                    > in an expect us to basically write their entire homework assignment, then
                    > we get ornery.
                    >
                    > Having said that, you just said that you've "decided to get with
                    > std::string", but I don't see a std::string _anywhere_ in this code...
                    >[color=green]
                    >> W7Graded.cpp
                    >>
                    >> /*------------------------------------------------------/*
                    >> /* Workshop 7 -- Graded Project /*
                    >> /* Jordan Tiona /*
                    >> /* Last Updated April 17, 2006 /*
                    >> /*------------------------------------------------------*/
                    >>
                    >> //Included Files
                    >>
                    >> #include <iostream>
                    >> #include <stdio.h>
                    >> #include "W7Graded.h "
                    >> using namespace std;
                    >>
                    >> //Function Prototypes
                    >>
                    >> void PrintData();
                    >> void EnterData();
                    >> void SaveData();
                    >> void LoadData();
                    >>
                    >> //Global Variables
                    >>
                    >> cdData* cd; //Linked List
                    >>
                    >> int main(){
                    >> cd = new cdData();
                    >> int choice;
                    >> bool quit = false;
                    >> while(quit == false){
                    >> system("cls");
                    >> cout << "Welcome to CD Tracker \n\n";
                    >>
                    >> cout << "What would you like to do?\n";
                    >> cout << "\t(1)Print Current Data\n";
                    >> cout << "\t(2)Enter New Data\n";
                    >> cout << "\t(3)Save Current Data\n";
                    >> cout << "\t(4)Load Data\n";
                    >> cout << "\t(5)Exit\ n";
                    >> cin >> choice;[/color]
                    >
                    > Warning... see what happens if a user doesn't enter a numeric value....
                    >[color=green]
                    >> switch(choice){
                    >> case 1: PrintData();
                    >> break;
                    >> case 2: EnterData();
                    >> break;
                    >> case 3: SaveData();
                    >> break;
                    >> case 4: LoadData();
                    >> break;
                    >> case 5: quit = true;
                    >> break;
                    >> default: cout << "\n Invalid choice. Please try again\n";
                    >> }
                    >> }
                    >> return 1;
                    >> }
                    >>
                    >> void PrintData(){
                    >>
                    >> cdData* curNode = cd;
                    >> char* tempStr;
                    >> int tempInt;
                    >>
                    >> system("cls");
                    >> do{
                    >> tempStr = curNode->GetName();
                    >> if(tempStr != NULL)
                    >> cout << "CD Name: " << *tempStr << endl;[/color]
                    >
                    > *tempStr is a character. You probably don't want to dereference tempStr
                    > here. (at least it appears that you're using it in the context of a
                    > C-style string...)
                    >[color=green]
                    >> cout << "-------------------------------------\n";
                    >> tempStr = curNode->GetArtist();
                    >> if(tempStr != NULL)
                    >> cout << "Artist: " << *tempStr << endl;[/color]
                    >
                    > Same as above.
                    >[color=green]
                    >> tempInt = curNode->GetYear();
                    >> cout << "Year Released: " << tempInt << endl;
                    >>
                    >> curNode = curNode->GetNext();
                    >> }while(curNode != NULL);
                    >> system("pause") ;
                    >> }
                    >>
                    >> void EnterData(){
                    >>
                    >> bool stop = false;
                    >> char *tempStr;
                    >> int tempInt;
                    >> cdData* curNode = cd;
                    >> char yn;
                    >>
                    >> tempStr = new char();[/color]
                    >
                    > tempStr is now pointing at enough memory to hold 1 char.... (Looking a
                    > little further forward, are you sure you don't want:
                    >
                    > tempStr = new char[MAX_LENGTH + 1];
                    >
                    > ? That is a "string" long enough to hold MAX_LENGTH, plus 1 character for
                    > the terminating 0-char (that is the char with the value 0, not the '0'
                    > character).
                    >[color=green]
                    >> //Get to the end of the linked list first
                    >> while(curNode->GetNext() != NULL){ //If there isn't anything after this
                    >> node, then this is the end of the list
                    >> curNode = curNode->GetNext(); //Go to the next Node
                    >> }
                    >>
                    >> while(stop == false){
                    >> system("cls");
                    >> cin.ignore();
                    >> //Add a new node
                    >> curNode->SetNext(new cdData());
                    >> curNode = curNode->GetNext();
                    >>
                    >> cout <<"\nName of CD: ";
                    >> cin.getline(tem pStr, MAX_LENGTH);[/color]
                    >
                    > Under your original code, this results in a "buffer overflow", and is
                    > likely to crash your program (but not guaranteed... this is what's called
                    > Undefined Behaviour).
                    >[color=green]
                    >> curNode->SetName(tempSt r);
                    >>
                    >> tempStr = new char();[/color]
                    >
                    > See above.
                    >[color=green]
                    >> cout <<"\n\nName of Artist: ";
                    >> cin.getline(tem pStr, MAX_LENGTH);[/color]
                    >
                    > See above.
                    >[color=green]
                    >> curNode->SetArtist(temp Str);
                    >>
                    >> cout <<"\n\nYear Released: ";
                    >> cin >> tempInt;
                    >> curNode->SetYear(tempIn t);
                    >>
                    >> system("cls");
                    >> cout <<"Enter another CD? (Y/N)\n";
                    >> cin >> yn;
                    >>
                    >> if(yn == 'Y' || yn == 'y')
                    >> stop = false;
                    >> else
                    >> stop = true;
                    >> }
                    >>
                    >> }
                    >>
                    >> void SaveData(){
                    >> }
                    >>
                    >> void LoadData(){
                    >> }
                    >>
                    >> W7Graded.h
                    >>
                    >> //CD Data
                    >> const int MAX_LENGTH = 21;
                    >>
                    >> class cdData {
                    >> private:
                    >> //CD Data
                    >> char* cdName;
                    >> char* artist;
                    >> int year;
                    >> //Linked List Data
                    >> cdData* next;
                    >> public:
                    >> //Constructor/Destructor
                    >> cdData(){next = NULL;
                    >> artist = NULL;
                    >> cdName = NULL;}[/color]
                    >
                    > Prefer initialization lists to initialization within the body. That is,
                    > write this instead:
                    >
                    > cdData() : next(NULL), artist(NULL), cdName(NULL) {};
                    >
                    > The advantage here (which doesn't mean much for a simple pointer, but more
                    > of an issue with more complex classes) is that in your form, the variables
                    > next, artist and cdName need to the default-initialized first, then
                    > assigned a value. With an initialization list, the variables would be
                    > constructed with the right values to begin with.
                    >[color=green]
                    >> ~cdData(){}
                    >> //Accessors
                    >> char* GetName(){retur n cdName;}
                    >> char* GetArtist(){ret urn artist;}
                    >> int GetYear(){retur n year;}
                    >>
                    >> void SetName(char* newName){cdName = newName;}
                    >> void SetArtist(char* newName){artist = newName;}
                    >> void SetYear(int newYear){year = newYear;}
                    >>
                    >> cdData* GetNext(){retur n next;}
                    >> void SetNext(cdData* newNext){next = newNext;}
                    >> };
                    >>
                    >> I can't put more than one character in the "cdName" variable. How do I
                    >> get more than one character (or more than one word for that matter)?[/color]
                    >
                    > Other items to note:
                    >
                    > 1) Your program leaks memory like a sieve. I see many instances of "new
                    > char" (which probably should be "new char[MAX_LENGTH + 1]"), but I don't
                    > ever see a call to "delete" (or delete[] if you fix the allocations).
                    > 2) This gets a whole lot easier if you change to std::strings. All of the
                    > dynamic memory stuff related to "strings" goes away.
                    > 3) If you're trying to read an entire line into a std::string, look up
                    > std::getline() (and not the getline() that is a member of a stream).
                    > 4) I'm assuming it's part of the assignment that you can't use the rest of
                    > the standard C++ library (like std::list, or some other container)?[/color]

                    Ok, well. I tried switching to strings, but I was getting a TON of errors
                    that made no sense. Another thing about using strings, is that they're not
                    mentioned once in my entire course (this is my last assignment). Char arrays
                    are all that are used. But it appeared that using a pointer was the only way
                    to use getline. Idk, I just never got it I guess. I think Ill try rewriting
                    the entire program (didn't take me /that/ long).


                    Comment

                    • Rolf Magnus

                      #11
                      Re: char* string?

                      Jordan Tiona wrote:
                      [color=blue][color=green]
                      >> 1) Your program leaks memory like a sieve. I see many instances of "new
                      >> char" (which probably should be "new char[MAX_LENGTH + 1]"), but I don't
                      >> ever see a call to "delete" (or delete[] if you fix the allocations).
                      >> 2) This gets a whole lot easier if you change to std::strings. All of
                      >> the dynamic memory stuff related to "strings" goes away.
                      >> 3) If you're trying to read an entire line into a std::string, look up
                      >> std::getline() (and not the getline() that is a member of a stream).
                      >> 4) I'm assuming it's part of the assignment that you can't use the rest
                      >> of the standard C++ library (like std::list, or some other container)?[/color]
                      >
                      > Ok, well. I tried switching to strings, but I was getting a TON of errors
                      > that made no sense.[/color]

                      I doubt that (not that you got a ton of errors, but that they made no
                      sense). I rather assume that you just didn't understand them.
                      [color=blue]
                      > Another thing about using strings, is that they're not mentioned once in
                      > my entire course (this is my last assignment).[/color]

                      Then that course is useless. std::string is a standard C++ class, and it
                      makes string handling a _lot_ simpler and safer. It should be explained
                      before raw arrays of char and manual memory handling.


                      Comment

                      • mlimber

                        #12
                        Re: char* string?

                        Jordan Tiona wrote:[color=blue]
                        > Ok, well. I tried switching to strings, but I was getting a TON of errors
                        > that made no sense. Another thing about using strings, is that they're not
                        > mentioned once in my entire course (this is my last assignment). Char arrays
                        > are all that are used. But it appeared that using a pointer was the only way
                        > to use getline. Idk, I just never got it I guess. I think Ill try rewriting
                        > the entire program (didn't take me /that/ long).[/color]

                        The fact that you never used std::strings implies that you probably
                        took a C-style course, even if you used a few features of C++. For a
                        good introduction to C++ from the ground up as C++ rather than C, see
                        Koenig and Moo's _Accelerated C++_. For an example of how to use
                        std::string and std::getline(), see this post:



                        Cheers! --M

                        Comment

                        • Jordan Tiona

                          #13
                          Re: char* string?

                          Ok, so I started to rewrite the program with a better linked list class, and
                          with strings. But it doesn't seem to recognize strings. I don't get why I'm
                          getting the errors I'm getting. Could you compile this and see what is
                          wrong? (BTW, I don't know if it is ok for me to give you two different
                          files, but I have two files here.)

                          W7Graded.cpp

                          #include <iostream>
                          #include <string>
                          #include "W7Graded.h "

                          using namespace std;

                          void EnterData();
                          void PrintData();
                          void SaveData();
                          void LoadData();

                          int main(){
                          LinkedList *cdList = NULL;
                          int choice;
                          bool quit = false;

                          while(quit == false){
                          system("cls");
                          cout << "Welcome to CD Tracker \n\n";

                          cout << "What would you like to do?\n";
                          cout << "\t(1)Print Current Data\n";
                          cout << "\t(2)Enter New Data\n";
                          cout << "\t(3)Save Current Data\n";
                          cout << "\t(4)Load Data\n";
                          cout << "\t(5)Exit\ n";
                          cin >> choice;

                          switch(choice){
                          case 1: PrintData();
                          break;
                          case 2: EnterData();
                          break;
                          case 3: SaveData();
                          break;
                          case 4: LoadData();
                          break;
                          case 5: quit = true;
                          break;
                          default: cout << "\n Invalid choice. Please try again\n";
                          }
                          }
                          return 1;
                          }

                          void EnterData(){
                          }

                          void PrintData(){
                          }

                          void SaveData(){
                          }

                          void LoadData(){
                          }

                          LinkedList::Lin kedList(){
                          hn = new cdData();
                          cn = hn;
                          }

                          LinkedList::~Li nkedList(){
                          this->RemoveAll();
                          }

                          void LinkedList::Ins ert(cdData* newCD){
                          cdData* temp = hn;

                          //Run to end of list
                          while(temp->GetNext() != NULL)
                          temp = temp->GetNext();

                          temp->SetNext(newCD) ;
                          }

                          void LinkedList::Rem oveAll(){
                          cdData* temp = hn;
                          this->Reset();

                          while(temp->GetNext() != NULL){
                          cn = temp;
                          temp = temp->GetNext();
                          delete cn;
                          }
                          delete temp;
                          hn->SetNext(NULL );
                          }

                          -------------------------------------------------------
                          W7Graded.h

                          class cdData{
                          private:
                          string name;
                          string artist;
                          string year;

                          cdData* next;
                          public:
                          cdData(){ next = NULL;}
                          ~cdData(){}

                          string GetName(){ return name;}
                          string GetArtist(){ return artist;}
                          string GetYear(){ return year;}
                          cdData* GetNext(){ return next;}

                          void SetName(string newName){ name = newName;}
                          void SetArtist(strin g newName){ artist = newName;}
                          void SetYear(string newYear){ year = newYear;}
                          void SetNext(cdData* newNext){ next = newNext;}
                          };

                          class LinkedList{
                          private:
                          cdData* hn; //Head Node
                          cdData* cn; //Current Node
                          public:
                          LinkedList();
                          ~LinkedList();

                          void Insert(cdData* newCD);
                          void RemoveAll();
                          void Reset(){ cn = hn;}
                          void GetNext(){ cn = cn->GetNext();
                          return cn;}
                          };
                          --------------------------------------------------

                          I'm trying not to break any rules, but if I am, than sorry in advance.



                          Comment

                          • mlimber

                            #14
                            Re: char* string?


                            Jordan Tiona wrote:[color=blue]
                            > Ok, so I started to rewrite the program with a better linked list class, and
                            > with strings. But it doesn't seem to recognize strings. I don't get why I'm
                            > getting the errors I'm getting. Could you compile this and see what is
                            > wrong? (BTW, I don't know if it is ok for me to give you two different
                            > files, but I have two files here.)[/color]
                            [snip][color=blue]
                            > W7Graded.h
                            >
                            > class cdData{
                            > private:
                            > string name;
                            > string artist;
                            > string year;
                            >
                            > cdData* next;
                            > public:
                            > cdData(){ next = NULL;}
                            > ~cdData(){}
                            >
                            > string GetName(){ return name;}
                            > string GetArtist(){ return artist;}
                            > string GetYear(){ return year;}
                            > cdData* GetNext(){ return next;}
                            >
                            > void SetName(string newName){ name = newName;}
                            > void SetArtist(strin g newName){ artist = newName;}
                            > void SetYear(string newYear){ year = newYear;}
                            > void SetNext(cdData* newNext){ next = newNext;}
                            > };
                            >
                            > class LinkedList{
                            > private:
                            > cdData* hn; //Head Node
                            > cdData* cn; //Current Node
                            > public:
                            > LinkedList();
                            > ~LinkedList();
                            >
                            > void Insert(cdData* newCD);
                            > void RemoveAll();
                            > void Reset(){ cn = hn;}
                            > void GetNext(){ cn = cn->GetNext();
                            > return cn;}
                            > };[/color]

                            The problem is that string isn't visible in your header file. If you
                            append "std::" before each instance of "string", that should get rid of
                            the errors. Also, it's generally best to include all headers that any
                            particular file needs directly. In this case, that would mean including
                            <string> in your .h file instead of the .cpp file. That way, you don't
                            have to include <string> manually in each file where you use that
                            header. Finally, "using namespace std;" is fine for .cpp files, but
                            don't be tempted to use it in your header. That will pollute the global
                            namespace for anyone who includes your file, which defeats the purpose
                            of namespaces.

                            Cheers! --M

                            Comment

                            • Tomás

                              #15
                              Re: char* string?

                              [color=blue][color=green]
                              >> class cdData{
                              >> private:
                              >> string name;
                              >> string artist;
                              >> string year;[/color][/color]


                              class cdData {
                              private:
                              typedef std::string string;

                              string name;
                              string artist;
                              string year;


                              -Tomás

                              Comment

                              Working...