Thread: C++ Code errors - i can't find the problem (new programmer)

  1. #1
    Registered User
    Join Date
    Jun 2005
    Posts
    3

    C++ Code errors - i can't find the problem (new programmer)

    Okay, i've been trying to teach myself C++ and have been using the site's excellent tutorials, however i have a problem.

    I wanted to create a simple program that collects input and then outputs it for experience.

    My problem is that after the first input (name in this case) the program closes, despite being only part way through the program.

    I've checked the code and it seems right to me....Can anyone tell me what the problem is? It's probably very simple, i'm new to this

    The code complied correctly......
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    int yourname;
    int youraddress;
    int yourage;
    
    cout<<"Welcome to program testing.  Thank you for deciding to become a beta tester.  Please enter your name. \n";
    cin>> yourname;
    cin.ignore();
    cin.get();
    cout<<"Please enter your address \n";
    cin>> youraddress;
    cin.ignore();
    cin.get();
    cout<<"Please enter your age \n";
    cin>> yourage;
    cin.ignore();
    cin.get();
    cout<<"Thanks.  Your details are as follows <<yourname \n youraddress \n yourage \n << \n";
    }
    NB: The actual text the program outputs is simply there to be there, it doesn't actually mean anything!

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Why is 'yourname' an integer? Also, you don't ever actually output any of your variables.


    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    3
    Why is 'yourname' an integer?
    What should it be? I'm new to this

    Also, you don't ever actually output any of your variables.
    Code:
    cout<<"Thanks.  Your details are as follows <<yourname \n youraddress \n yourage \n << \n";
    This line is the output

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    What should it be? I'm new to this
    Will, think about it. Is your name a number? Mine isn't.


    This line is the output
    No it isn't. You're not paying attention to your quotation marks.

    Code:
    cout<<"Thanks.  Your details are as follows <<yourname \n youraddress \n yourage \n << \n";
    Everything between quotation marks denotes a single string of text. Your output will be exactly the text in between the quotation marks.


    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Feb 2005
    Location
    oslo
    Posts
    26
    Code:
    cout<<"Thanks.  Your details are as follows <<yourname \n youraddress \n yourage \n << \n";
    This line is the output

    Still it wont print the content of the variables!

    you need to have it

    Code:
    cout<<"Thanks.  Your details are as follows " << yourname << "\n" << youraddress << "\n" << yourage << "\n\n";
    But instead of newlines, you should make a habit of using std::endl instead.


    Code:
    cout<<"Thanks.  Your details are as follows " << yourname << endl << youraddress << endl << yourage << endl << endl;

    since endl also clears the output buffer
    life is too short smart but hard !

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    3
    thanks - that makes more sense.

    However, when i compile and run the program it still crashes after the first varible is entered.

    What should it be? I'm new to this
    Will, think about it. Is your name a number? Mine isn't.
    So what should it be? (i presume this is the problem)

  7. #7
    Registered User
    Join Date
    Feb 2005
    Location
    oslo
    Posts
    26
    use strings or chars


    with chars:

    Code:
        
    char name[20]; // a variable that can hold 20 chars
    cin >> name;



    with strings you need to include <cstring> and then:


    Code:
    string name;
    cin >> name;
    life is too short smart but hard !

  8. #8
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    there are two basic types of strings you can use to hold characters.

    C style strings are null terminated char arrays. You don't need to include any headers other than iostream to declare or use C style strings if all you do is accept input into and display the string to the screen. However, if you want to manipulate the string, such as copy the string to a different one, concatenate the string onto a different one, determine the number of non-null char in the string, etc., then you need to include the cstring library (or maybe string.h if you have an older compiler). You declare C style strings like this:

    char myString [] = "my string";

    or this:

    char myString * = "my string";

    or this:

    char myString[30];

    in addition to other options.
    The other basic type of string is an instance of the STL string class. To use this class you need to include the string library. The string class includes a method called c_str() that allows you to access the C style string buried within the string object. The string class allows you to do things with the string object like copy, concatenate, etc. just as you can with C style strings directly, but the syntax is generally more user friendly, and you don't have the hassles of doing your own memory management. To declare a object of the string class you do this:

    string myString;

    If you do this:

    #include <cstring>

    without also declaring this:

    #include <string>

    and declare a string variable like this:

    string myString;

    you will get an error because you have included the file to maniplulate C style strings, but are declaring an STL string instead.
    You're only born perfect.

  9. #9
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Quote Originally Posted by Dag_
    with strings you need to include <cstring> and then:


    Code:
    string name;
    cin >> name;

    You need to include <string> and not <cstring> to use the string container. <cstring> is for prototypes of functions like strcpy, strcmp, etc.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  10. #10
    Registered User
    Join Date
    Jan 2003
    Posts
    311
    Quote Originally Posted by elad
    char myString [] = "my string";

    or this:

    char myString * = "my string";

    or this:

    char myString[30];
    These are not the same things, although they all "work". Part of the joy and problem with c is that it's so easy to get confused. Pointers and arrays can usually be interchanged freely.
    Code:
    char myString[] = "my string";
    declares an array [] of size big enough to hold "my string" and a terminating zero. It will contain "my string" before you use it.
    Code:
    char *myString = "my string"
    is a pointer to a string literal, you can read but never touch. myString is big enough to hold a pointer , regardless of how big the literal "my string" is.
    Code:
    char myString[30]
    has space for 29 readable, usefull characters and 1 terminating zero, it's value is undefined, you can touch but only read after you touch.

    The reason your program is crashing is only partially related to strings (and you should just use the c++ style std::string and ignore c style strings for now) What happens when you attempt to read something the program doesn't understand is all reads fail silently until you acknowlage the problem by calling std::cin.clear()
    Code:
    #include<iostream>
    #include<string>
    
    int main ()
        std::string name;
            std::cout << "what's your name?\n:"
            while(std::getline(std::cin, name) && name != "quit") {
                int age;
                std::cout << "I think your name is " << name 
                               << "\n how old are you?\n:";
                if(std::cin >> age) {
                    std::cout << "I think your age is " << age << '\n';
                } else {
                    std::cout << "I have no idea how old you are\n";
                    std::cin.clear();
                }
                std::cout << "Enter quit to stop this, or a new name to play again" 
                               << std::endl;
        }
        return 0;
    }
    This program pays attention to the state of the stream, in general you should wrap all input operations in some form of conditional. The earlyer you catch errors the faster you can get the user to enter what's expected, or start doing what the user expects.

  11. #11
    Registered User
    Join Date
    May 2005
    Posts
    73
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      char yourname[20];  // Yourname 20 characters long.
      char youraddress[30]; // Youradress 30 characters long.
      int yourage; // Yourage is an integer.
    
      cout<<"Please enter your name. \n";
      cin.getline(yourname, 20, '\n');  // Get the entire line including spaces up to 20 characters.  Stop if newline character is read (i.e. ENTER)
    
      cout<<"\nPlease enter your address \n";
      cin.getline(youraddress, 30, '\n');  // Get the entire line including spaces up to 30 characters.  Stop if newline character is read (i.e. ENTER)
    	
      cout<<"\nPlease enter your age \n";
      cin >> yourage; // Get yourage.  CIN >> is used as no spaces need to be read.  CIN >> only reads up until a space is reached.
    
      cout << "\nThanks.  Your details are as follows\n" << yourname << endl << youraddress << endl << yourage << endl << endl;  // Output results.  Variables cannot be in quotations.  While text is inside quotations.
    
      return 0;
    }

  12. #12
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Okay, i've been trying to teach myself C++ and have been using the site's excellent tutorials
    You are most likely never going to learn C++ reading one page tutorials(the fact that you tried to assign a name to a variable of type integer is a pretty good indication of that). Get a beginning C++ book if you really want to learn the language.

  13. #13
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Grib: No argument, C style strings are more difficult to use than STL strings. And no argument the distinction between arrays and pointers is subtle. Whether you call myString in the following declaration to be a char pointer or a C style string is up to you. To my understanding, which admittedly is not encyclopedic, except for being unable to change the char in myString it acts exactly like a C style string.

    char * myString = "Hello World";

    Therefore, if it acts like a C style string I call it a C style string, even though in technical terms it may or may not be a C style string in addition to being a pointer.

    As to clear(), my understandin is it resets the state flags of the stream to their default values; it won't "clear" the stream of unwanted char. Therefore, it will not clear the newline char, or other terminating whitespace char, left in the input buffer after a call to >>. If you want to clear the newline char, or any other char(s), from the stream before reusing the stream again you must use ignore(), not clear().
    You're only born perfect.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compile Errors in my Code. Can anyone help?
    By DGLaurynP in forum C Programming
    Replies: 1
    Last Post: 10-06-2008, 09:36 AM
  2. Problem in simple code.
    By richdb in forum C Programming
    Replies: 6
    Last Post: 03-20-2006, 02:45 AM
  3. Help with code for simple Y2K problem
    By Mule in forum C++ Programming
    Replies: 3
    Last Post: 03-06-2003, 12:53 AM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. can anyone find the problem in my code
    By ArseMan in forum C++ Programming
    Replies: 2
    Last Post: 09-20-2001, 09:02 PM