Hello World V 3

This is a discussion on Hello World V 3 within the C++ Programming forums, part of the General Programming Boards category; I am just starting to learn C++ and having a wonderful time with it. Here are my questions: 1: How ...

  1. #1
    SRS
    SRS is offline
    3rd Week In C++ SRS's Avatar
    Join Date
    Nov 2007
    Posts
    22

    Hello World V 3

    I am just starting to learn C++ and having a wonderful time with it.
    Here are my questions:
    1: How could I use 1 function to do the work of getting and returning both names, the shortest way possible?
    2: I can not find how to compare strings in the if (which is why it compares 1 & 2 rather than Y & N)
    3: I would like to find out how to return to verify name if an invalid answer is given.

    Code:
    // Hello World! V 3_00_00
    // Use of functions and variables
    // by SRS
    
    #include <iostream.h>
    #include <string>
    
    using namespace std;
    
    string firstName;
    string lastName;
    void first_name()
    {
       cout << "Please Enter Your First Name:" << endl;
       cin >> firstName;
    }
    void last_name()
    {
       cout << "Please Enter Your Last Name:" << endl;
       cin >> lastName;
    }
    // I am sure there is a way to use 1 function to return both names individually
    
    
    void main()
    {
       first_name();
       last_name();
       string fullName = firstName + " " + lastName;
       cout << "Please verify your correct name is " <<  fullName << endl;
       cout << "By entering '1' if it is correct" << endl;
       cout << "or '2' if it is incorrect:" << endl;
    
    // *Returning Point
       int verify;
       cin >> verify;
       if(verify == 1)  //  Can not figure out how to compare strings
       {
          cout << "Hello World, from " << firstName << " " << lastName << "!!"<< endl;
          cin.get();
       }
       else if(verify == 2)  //  Can not figure out how to compare strings
       {
          cout << "Please try again:\n" << endl;
          main();
       }
       else
       {
          cout << "I have no idea how to return to the verify from here" << endl;
    // Would like to know if it is possible to jump from here to *Returning Point
          cin.get();
       }
       cin.get();
    }
    Thank you in advance for helping me learn C++

  2. #2
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,475
    A few things with your program:

    void main should be int main() or int main ( void )
    <iostream.h> is an old header. Use <iostream> and drop the .h

    Never call the main() function from within a program. Its sole purpose is to act as the starting point of a program.
    I'm just trying to be a better person - My Name Is Earl

  3. #3
    Registered User
    Join Date
    May 2007
    Posts
    77
    Also, at one point, you combine firstName and lastName into fullName, when you could just skip that line of code and output both variables the same way you put them into fullName.

    And you do need int to declare your main, not void.

    In answer to your one function question, just take the code inside your firstName and lastName functions and put the code where you called those functions in main. They are already as small as you can get them.

    And as for comparing strings, thankfully, you don't have to (I'm not sure how to do that myself). You only have to compare characters, which is possible, and easy. First, make sure to declare "char verify" instead of "int verify", and then, when comparing, do like so:
    Code:
    if ((verify == 'y') || (verify == 'Y'))
    {
        //conditional code here
    }
    The reason I have both the lower case and the upper case in there is because if you only have "Y" in the conditional, and the user inputs "y", the program will decide that the conditional was not met. The logical OR operator "||" allows for either occurrence to happen for a success.

    You can use the same type of comparison to make a loop around the name verification process, such as do...while. You tell it to do (automatically run once) the name verification, and set the conditional to be "while (!((verify == 'y') || (verify == 'Y') || (verify == 'n') || (verify == 'N'));". This is just what I've found to work, and if there's a shorter way to do that, then tell me, please.

    Finally, you'd probably want to put a loop around the name entry process AND the name verification loop to provide for the possibility that the person didn't enter their name correctly. That will eliminate the seeming need to call main() from within itself.

  4. #4
    Registered User mikeman118's Avatar
    Join Date
    Aug 2007
    Posts
    183
    You could use a char, but to compare to strings is very simple (I am puzzled as to why people don't know this):
    Code:
    string str1 = "Hello, world!";
    string str2 = "Goodbye, world!"
    if (str1 == str2)
    ...
    Of course, that would not be true, but that's how you would do it.

    Also, I'm pretty sure it's not possible to call main() from inside your application. If you tried to compile that you would get an error.

  5. #5
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,604
    Quote Originally Posted by SRS View Post
    I am just starting to learn C++ and having a wonderful time with it.
    Here are my questions:
    1: How could I use 1 function to do the work of getting and returning both names, the shortest way possible?
    Yes, declare a function that takes two arguments by reference:
    Code:
    void getnames(string& firstname, string& lastname);
    Quote Originally Posted by SRS View Post
    2: I can not find how to compare strings in the if (which is why it compares 1 & 2 rather than Y & N)
    The correct C++ way would be to use the string class. Then all you need to do is:
    Code:
    string s1 = "hello world!";
    if (s1 == "hello world!"); // When comparing a string
    if (s1 == 'Y'); // When comparing to a character
    Quote Originally Posted by SRS View Post
    3: I would like to find out how to return to verify name if an invalid answer is given.
    As noted, use a loop. I find it easiest to break the loop when conditions are met:

    Code:
    // Hello World! V 3_00_00
    // Use of functions and variables
    // by SRS
    
    #include <iostream.h>
    #include <string>
    
    using namespace std;
    
    string firstName;
    string lastName;
    void first_name()
    {
       cout << "Please Enter Your First Name:" << endl;
       cin >> firstName;
    }
    void last_name()
    {
       cout << "Please Enter Your Last Name:" << endl;
       cin >> lastName;
    }
    // I am sure there is a way to use 1 function to return both names individually
    
    int main() // Main should always return INT
    {
       first_name();
       last_name();
       string fullName = firstName + " " + lastName;
       cout << "Please verify your correct name is " <<  fullName << endl;
       cout << "By entering '1' if it is correct" << endl;
       cout << "or '2' if it is incorrect:" << endl;
    
    // *Returning Point
       int verify;
    for(;;)
    {
       cin >> verify;
       if(verify == 1)  //  Can not figure out how to compare strings
       {
          cout << "Hello World, from " << firstName << " " << lastName << "!!"<< endl;
          cin.get();
    	break; // Break the loop
       }
       else if(verify == 2)  //  Can not figure out how to compare strings
       {
          cout << "Please try again:\n" << endl;
    	continue; // You can continue but you don't need to since the loop will begin over if the user a correct answer.
       }
       else
       {
          cout << "I have no idea how to return to the verify from here" << endl;
    // Would like to know if it is possible to jump from here to *Returning Point
    	continue;
       }
    }
    }
    Quote Originally Posted by swgh View Post
    Never call the main() function from within a program. Its sole purpose is to act as the starting point of a program.
    I don't really see a problem with that. It's a function like any else. But you probably won't do it since any code that's recursive will probably reside in its own function.

    Quote Originally Posted by Molokai View Post
    And as for comparing strings, thankfully, you don't have to (I'm not sure how to do that myself). You only have to compare characters, which is possible, and easy. First, make sure to declare "char verify" instead of "int verify", and then, when comparing, do like so:
    Code:
    if ((verify == 'y') || (verify == 'Y'))
    {
        //conditional code here
    }
    The reason I have both the lower case and the upper case in there is because if you only have "Y" in the conditional, and the user inputs "y", the program will decide that the conditional was not met. The logical OR operator "||" allows for either occurrence to happen for a success.[/code]
    The only problem here is that if you use a single char for input, you'll get a buffer overrun (since it always always write a '\0' at the end of the array). At least you need to do an array 2 two elements. But that's risky too if the user enters more than one char. No, just use string.

    [QUOTEMolokai;684731]You can use the same type of comparison to make a loop around the name verification process, such as do...while. You tell it to do (automatically run once) the name verification, and set the conditional to be "while (!((verify == 'y') || (verify == 'Y') || (verify == 'n') || (verify == 'N'));". This is just what I've found to work, and if there's a shorter way to do that, then tell me, please.
    It's easier just to do a never-ending loop and use continue and break to control its flow. Because it's much easier to read.

    Quote Originally Posted by mikeman118 View Post
    Also, I'm pretty sure it's not possible to call main() from inside your application. If you tried to compile that you would get an error.
    Sure it is!
    Code:
    int main()
    {
    	main();
    	return 0;
    }
    Sure, it will loop forever and you'll probably get a warning, but it works just fine (compiles without a hitch).

  6. #6
    SRS
    SRS is offline
    3rd Week In C++ SRS's Avatar
    Join Date
    Nov 2007
    Posts
    22

    :) Ty All

    Quote Originally Posted by swgh View Post
    A few things with your program:

    void main should be int main() or int main ( void )
    <iostream.h> is an old header. Use <iostream> and drop the .h
    Thanks for the tip, can you explain int main(void) vs int main(), and if using either of these will I also have to return a value at the end? ie return 0;
    Quote Originally Posted by swgh View Post
    Never call the main() function from within a program. Its sole purpose is to act as the starting point of a program.
    Thanks again, how should I return to the beginning?

    --------------------------------------------------------------------------------------------------------------

    Quote Originally Posted by Molokai View Post
    Also, at one point, you combine firstName and lastName into fullName, when you could just skip that line of code and output both variables the same way you put them into fullName.

    And you do need int to declare your main, not void.

    In answer to your one function question, just take the code inside your firstName and lastName functions and put the code where you called those functions in main. They are already as small as you can get them.
    Is there not a way to pass a variable back to main from a function?
    In another language it is possible by passing the input from the function back to the main through a function parameter. I do not know enough about C++ yet to know if that is even possible.
    Quote Originally Posted by Molokai View Post
    And as for comparing strings, thankfully, you don't have to (I'm not sure how to do that myself). You only have to compare characters, which is possible, and easy. First, make sure to declare "char verify" instead of "int verify", and then, when comparing, do like so:
    Code:
    if ((verify == 'y') || (verify == 'Y'))
    {
        //conditional code here
    }
    The reason I have both the lower case and the upper case in there is because if you only have "Y" in the conditional, and the user inputs "y", the program will decide that the conditional was not met. The logical OR operator "||" allows for either occurrence to happen for a success.

    You can use the same type of comparison to make a loop around the name verification process, such as do...while. You tell it to do (automatically run once) the name verification, and set the conditional to be "while (!((verify == 'y') || (verify == 'Y') || (verify == 'n') || (verify == 'N'));". This is just what I've found to work, and if there's a shorter way to do that, then tell me, please.

    Finally, you'd probably want to put a loop around the name entry process AND the name verification loop to provide for the possibility that the person didn't enter their name correctly. That will eliminate the seeming need to call main() from within itself.
    Yes I understand the need for Y and y as acceptable replies, that leads into questions I reserved for later like how to force an input string into all lowercase rather than trying to check things like Yes, YES, yEs etc..
    Unfortunately if(veryfy == "y") caused compile error stating:
    "ANSI C++ forbids comparison between pointer and integer"
    Which I did not understand because verify was declared as a string variable and I thought "Y" was also a string, so how is this comparing an integer? However I notice now you used 'y' and I used "Y".. what is the difference there? Single quote marks compiles and compares the character while the double quote marks causes compile error.

    --------------------------------------------------------------------------------------------------------------

    Quote Originally Posted by mikeman118 View Post
    You could use a char, but to compare to strings is very simple (I am puzzled as to why people don't know this):
    Code:
    string str1 = "Hello, world!";
    string str2 = "Goodbye, world!"
    if (str1 == str2)
    ...
    Of course, that would not be true, but that's how you would do it.

    Also, I'm pretty sure it's not possible to call main() from inside your application. If you tried to compile that you would get an error.
    Comparing string variable to string variable works fine, I had no trouble with that, it was comparing a string variable to a definate- hard coded string... Its the problem with '' and "" marks that I am not understanding which seems to be the problem. However the full code I posted V_3_00_00 compiles and executes error free. (with the exception of runtime errors in that the script does not operate the way it is desired)

    Thank you, swgh, Molokai, and mikeman118 all 3 for your reply.
    Attached Images Attached Images  

  7. #7
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    >> can you explain int main(void) vs int main()
    They are the same in C++. Use int main() since that is the normal way to do it.

    >> will I also have to return a value at the end? ie return 0;
    With a proper compiler you don't. For normal functions you would, but main is special in that you can write int main() but leave out the return 0 and the compiler will return 0 for you.

    >> Thanks again, how should I return to the beginning?
    Use a loop. You can also create a separate function that handles most of what is in your main function and then call that recursively. It's just that main is special and you shouldn't call it like a normal function.

    >> Is there not a way to pass a variable back to main from a function?
    Yes, you can return it. You can also pass a parameter or multiple parameters by reference so that the variable(s) in main are updated.

    Single quotes in C++ indicate a single character of type char. So 'a' is a character. Double quotes indicates a string, so "a" is a string even though it includes only one character.

    The C++ string class holds a string, so to compare a string variable to a literal string the literal string has to have double quotes, so this should work:
    Code:
    std::string str = "y";
    if (str == "y")
    If you want to check upper and lower together, you have to lower each character separately. Or, you could just make your variable a char and read in a single character:
    Code:
    char ans;
    cin >> ans;
    if (tolower(ans) == 'y')

  8. #8
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,604
    Quote Originally Posted by SRS View Post
    Thanks for the tip, can you explain int main(void) vs int main(), and if using either of these will I also have to return a value at the end? ie return 0;

    Thanks again, how should I return to the beginning?
    int main() and int main(void) is the same in C++.
    Usually, you return 0 at the end, but it's really up to you.

    Quote Originally Posted by SRS View Post
    Is there not a way to pass a variable back to main from a function?
    In another language it is possible by passing the input from the function back to the main through a function parameter. I do not know enough about C++ yet to know if that is even possible.
    Quite possible. See references which I replied about above.

    Quote Originally Posted by SRS View Post
    Yes I understand the need for Y and y as acceptable replies, that leads into questions I reserved for later like how to force an input string into all lowercase rather than trying to check things like Yes, YES, yEs etc..
    There are member functions in the string class, I believe that can convert it all into lower case.

    Quote Originally Posted by SRS View Post
    Unfortunately if(veryfy == "y") caused compile error stating:
    "ANSI C++ forbids comparison between pointer and integer"
    Which I did not understand because verify was declared as a string variable and I thought "Y" was also a string, so how is this comparing an integer? However I notice now you used 'y' and I used "Y".. what is the difference there? Single quote marks compiles and compares the character while the double quote marks causes compile error.
    verify has to be an int if you get that error.
    As for the difference between " and ', 'y' == char, "y" == char* (pointer).
    What is actually means is that "y" is the same as 'y', '\0'. When you compare just one character, use '. Otherwise, if you compare a string, use ".

  9. #9
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    >> There are member functions in the string class, I believe that can convert it all into lower case.
    There aren't any for the string class. You have to loop through and lower each character separately. You can do it in a single line of code with an algorithm.

  10. #10
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,604
    The more I look at string, the more useless it seems.
    There are no alternative good string classes in any library such as boost?

  11. #11
    SRS
    SRS is offline
    3rd Week In C++ SRS's Avatar
    Join Date
    Nov 2007
    Posts
    22

    Daved & Elysia TY

    Quote Originally Posted by Daved View Post
    1. Use int main() since that is the normal way to do it.
    2. With a proper compiler you don't. ...and the compiler will return 0 for you.
    3. You can also create a separate function that handles most of what is in your main
    4. Single quotes in C++ indicate a single character of type char. Double quotes indicates a string.
    5.
    code]char ans;
    cin >> ans;
    if (tolower(ans) == 'y')[/code]
    1. Got it
    2. Using Dev-C++ and it does ty
    3. Working on that now, may have questions...
    4. Got it, that was actually my problem I had used char verify
    expecting a letter reply and compared to "Y"(string)
    5. Good show... tolower is exactly what I had in mind TY greatly

    ----------------------------------------------------------------------------------------------------------------
    Elysia
    TY so much. I am working on the excellent sample you put up with my code introducing the for loop. (I errored as far as the return point I found out when I ran it, as a reply of 2 sends it into the endless loop, but starting the loop above the function calls at the beginning of main worked as intended) TYVM for the help.

  12. #12
    Registered User
    Join Date
    Jan 2005
    Posts
    7,317
    >> The more I look at string, the more useless it seems.
    I completely disagree with your opinion of string, but feel free to start a thread on it if you'd like to discuss it. Short answer is that many C++ experts feel the class is too bloated, while you seem to want it to have more functions. Also, if you can make the string lowercase in a single line of code, why does it matter that it doesn't use a member function?

  13. #13
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,183
    AFAIK it is forbidden in standard C++ to call main() recursively

    because compilers may add additional initialization code at the beginning of main, that shouldn't be called more than once per execution

  14. #14
    Registered User
    Join Date
    May 2007
    Posts
    77
    Thank you, Daved, for clarifying that for him. Apparently, when I used the single quotes in my post, I wasn't clear enough.

    @SRS I am glad that you are getting it. I was afraid that some of what I said might be misunderstood, but it I am glad I could help.

    @mikeman118 I've tried that before, but for some reason I kept getting errors. I guess I'll have to go back to it and tweak it until it works.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. The 7 New Wonders of the World
    By Mario F. in forum A Brief History of Cprogramming.com
    Replies: 36
    Last Post: 12-08-2006, 12:55 PM
  2. Obfuscated Code Contest: The Results
    By Stack Overflow in forum Contests Board
    Replies: 29
    Last Post: 02-18-2005, 04:39 PM
  3. Converting from Screen to World Coordinates
    By DavidP in forum Game Programming
    Replies: 9
    Last Post: 05-11-2004, 12:51 PM
  4. Too much to ask ?
    By deflamol in forum C Programming
    Replies: 2
    Last Post: 05-06-2004, 04:30 PM
  5. No More Technology After World War Three
    By Unregistered in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 09-20-2001, 07:02 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21