Thread: Chapter 4 Practice Problems 4 and 5

  1. #16
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Osman Zakir
    Anyway, @Laserlight, could you explain how the stoi function would be useful here? I'm sorry, but I just want to know because I can't think of anything right now.
    It would be useful to convert the line read as a string to int. Consider:
    Code:
    #include <iostream>
    #include <string>
    
    int main()
    {
        std::string s = "123";
        int x = stoi(s);
        std::cout << x << std::endl;
        return 0;
    }
    Quote Originally Posted by Osman Zakir
    do exactly, and what should I have it do within the scope of those braces?
    It reads a line as a string and converts it to an int. Within the scope of those braces you would work with the int.

    Quote Originally Posted by Osman Zakir
    I want to study both C++11 and C++14, but Code::Blocks only seems to have support for C++ up to C++11. And Stroustrup's Programming: Principles and Practice using C++ 2nd Edition has info on both C++11 and C++14.
    Although it is a bigger update to the C++ standard than C++03 was to C++98, C++14 is nonetheless a much smaller update to the C++ standard than C++11, so I would not worry about the differences for now.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  2. #17
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by laserlight View Post
    Although it is a bigger update to the C++ standard than C++03 was to C++98, C++14 is nonetheless a much smaller update to the C++ standard than C++11, so I would not worry about the differences for now.
    But still brings a lot of useful stuff to the language, so I would say you should care. Of course, being so new means also that realistically there isn't going to be much code out there that uses it and given it requires such recent compilers, it is unlikely that you'll find a company using the latest standard in their codebase.

    But for learning, I say go all out.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #18
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    @Laserlight: Okay, thanks. I'll try it once I've upgraded GCC in Code::Blocks.

    @Elysia: I know about Code::Blocks being an IDE and not a compiler, and I also know that in my case, GCC is the compiler. I only meant that mine probably didn't have support for C++14 - and since it's just version 4.7.1, it probably really doesn't. So I'm going to download Code::Blocks with MinGW again, this time with GCC 4.8.1. Then I should be able to use "-std=c++14" flag in Project's Build Options without problems.

    If I have to tell Code::Blocks in file settings where those files are, where in Code::Blocks do I have to navigate to do that? I did once before, but I don't remember how anymore.

    Edit: It's giving me this error when I try use the C++14 standard:
    "mingw32-gcc-4.8.1.exe: error: unrecognized command line option '-std=c++14'"

    How do I fix it?
    Last edited by Osman Zakir; 03-26-2015 at 05:23 AM.

  4. #19
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I believe there is at least a mingw based on 4.8.3, so get the latest and install it.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #20
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    There's a 4.9.3 now, but I'm having trouble getting it right in Code::Blocks right now, for some reason.

    I tried using cin.ignore(), but it still exits right after asking whether I have any other family members to the information for, without taking any input.

    Code:
    #include <iostream>
    
    using namespace std;
    
    struct PersonalInfo
    {
        string name;
        string home_address;
        int phone_number;
    };
    
    PersonalInfo *personalInfo(PersonalInfo next_member[], int number_of_family_members);
    
    int main()
    {
        int number_of_family_members;
        char answer;
        PersonalInfo person;
        cout << "Personal Information Form:\n";
        cout << "\n";
        cout << "Please provide your name: ";
        getline(cin, person.name, '\n');
        cout << "Please provide your home address: ";
        getline(cin, person.home_address, '\n');
        cout << "Please provide your phone number: ";
        cin >> person.phone_number;
        //cin.ignore();
        cout << "Hello, " << person.name << ", your phone number and address have\n";
        cout << "successfully been noted.";
        cin.ignore();
        cout << " Are there any other family members whose information you would like to be noted?\n";
        cin >> answer;
        if (answer == 'Y' || answer == 'y')
        {
            cout << "How many other family members are there? ";
            cin >> number_of_family_members;
            cin.ignore();
            PersonalInfo* next_member = new PersonalInfo[number_of_family_members];
            personalInfo(next_member, number_of_family_members);
            delete[] next_member;
            next_member = NULL;
        }
        else if (answer == 'N' || answer == 'n')
        {
            cout << "Very well.  Thank you for your cooperation\n";
            return 0;
        }
    
    }
    
    PersonalInfo *personalInfo(PersonalInfo next_member[], int number_of_family_members)
    {
        for (int i = 0; i < number_of_family_members; i++)
        {
            cout << "Please provide name of family member: ";
            getline(cin, next_member[i].name, '\n');
            cout << "Please provide home address of family member: ";
            getline(cin, next_member[i].home_address, '\n');
            cout << "Please provide phone number of family member: ";
            cin >> next_member[i].phone_number;
            cout << "This was information for family member number: " << i + 1 << endl;
        }
    
        for (int i = 0; i < number_of_family_members; i++)
        {
            cout << next_member[i].name << "\n";
            cout << next_member[i].home_address << "\n";
            cout << next_member[i].phone_number << "\n";
        }
        return next_member;
    }
    Thanks in advance.

  6. #21
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Look at line 60. You have no following std::cin.ignore().
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #22
    Guest
    Guest
    While it doesn't hurt to return the pointer in this instance, I hope you're aware by now that it's superfluous in your code.
    Code:
    void personalInfo(PersonalInfo next_member[], int number_of_family_members)
    ...would work just the same.

  8. #23
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    Quote Originally Posted by Elysia View Post
    Look at line 60. You have no following std::cin.ignore().
    Why do I need it there, though? The part that's giving me problems, the one where the code exits, is Line 31, where it asks if there are any other family members. Although, maybe I really need to put cin.ignore() at some other part of the code as well . . . if so, please tell me where and why (you did tell me where just now, for example, but you missed the "why" - just saying).

    @Adrian: Alright, point taken. I'll change the function's return type to "void," then.

  9. #24
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by Osman Zakir View Post
    Why do I need it there, though? The part that's giving me problems, the one where the code exits, is Line 31, where it asks if there are any other family members. Although, maybe I really need to put cin.ignore() at some other part of the code as well . . . if so, please tell me where and why (you did tell me where just now, for example, but you missed the "why" - just saying).
    Normally when you extract from cin there is some detritus.

    After someone enters all their garbage -
    Code:
    John Doe\n
    123 Main St\n
    3135553459\n
    getline() will discard \n when it is encountered.

    cin >> sort of does. What usually happens is this. Take this stream buffer [^ is the stream get pointer]
    Code:
    John Doe\n123 Main St
             ^
    Say you wanted to extract the house number as an integer next (just for the purposes of demonstrating) - that works. cin will skip the white space in this case and read the house number next.

    char is exempt from this behavior. So what your stream buffer actually looks like is this:
    Code:
    3135553459\n
              ^
    And when you ask for an answer, the white space character is returned.

    This is why it can be important to do a cin.ignore() call just after you finish using cin >>. But then there might not be any input in the stream to discard, so you get a blinking cursor instead...

    This is why you might hear the advice to always use getline() because it is just easier. Grab everything and, validate/parse/ convert where needed. Easier than handling all of the pitfalls you can fall into.

  10. #25
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I want to sum it up as...
    First of all, streams are line buffered, so all I/O calls waits until the user presses enter, so that means the final character in the input buffer will be a \n.
    Now let's talk about the behaviors or std::cin >> [integer] and std::getline.

    Example buffer: Hello World!\n
    std::cin >> reads nothing, leaves "Hello World!\n" in buffer.
    std::getline reads everything and discards the \n, so it reads "Hello World!" and leaves nothing in the input buffer.

    Example buffer: 123\n
    std::cin >> reads 123 and leaves the \n in the input buffer.
    std::getline reads everything and discards the \n, so it reads "Hello World!" and leaves nothing in the input buffer.

    Example buffer: \n
    std::cin >> skips the \n and because the input buffer becomes empty, it asks the user for more input.
    std::getline reads the \n, discards it and returns an empty string. The input buffer becomes empty.

    Example buffer \n123\n (happens if you read with std::cin >> and then reads with std::cin >> again)
    std::cin >> skips the leading \n and reads 123, leaving the \n in the input buffer.

    So therefore we can see that if we do

    std::cin >> [integer var]; (1)
    std::getline(std::cin, string); (2)

    User enter 123, so buffer becomes 123\n.
    std::cin >> reads 123, leaves \n.
    std::getline reads \n and happily returns instead of asking for more input.

    So you need to flush the input buffer and one way to do that is std::cin.ignore(). By default, it flushes one character, but this is sufficient in your case.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  11. #26
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    My address in Pakistan, I believe, is Nazimabad Block 4, Flat B12/1, Karachi. I'm not sure what the road's name is, but Nazimabad is the area/neighborhood (something along those lines) and Karachi is the city. The name of the province is Sindh (although Karachi is towards outer edge and generally doesn't count as part of Sindh). I type "Nazimabad Block 4, B12\1, Karachi" and my mom's phone number without any hyphens or spaces, and then it exits right after asking if there are any other family members. Without taking any more input. When I entered something really short as an address (well, really, it was just gibberish), it went completely fine and didn't exit prematurely. Is there any way for it to accept longer strings of input without exiting too early?

    Also, are you guys suggesting I use getline() instead of cin all the time? But then will I able to use an int-type variable as an argument, since it seems to only accept string variables as one of the arguments? Or should I just type-cast the string to an int or use the function that turns any non-string variable into a string (what's the name again? And what library do I include to use it? And is it in C++11 or C++14?)?

  12. #27
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Osman Zakir View Post
    Also, are you guys suggesting I use getline() instead of cin all the time? But then will I able to use an int-type variable as an argument, since it seems to only accept string variables as one of the arguments? Or should I just type-cast the string to an int or use the function that turns any non-string variable into a string (what's the name again? And what library do I include to use it? And is it in C++11 or C++14?)?
    Yes, it will avoid many headaches with reading input. You read the entire input to ensure that next time you ask for something, it will ask the user instead of consuming (possibly) already existing data. You then sanitize the input (i.e. make sure it's valid; if you want them to enter a month of the year, for example, check if it's in the correct format) and convert it to the appropriate type as necessary.

    You can convert strings to integers via stoi as laserlight mentioned in post #16. stoi is C++11.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #28
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    getline requires the second argument to be a string, so I can't use an int, right? I tried using getine while passing in an int as the second argument, but it didn't accept it, and trying to turn it into a string via a type-cast or to_string also didn't work, and sometimes it even thought I'd only passed it one or two arguments rather than three.

    And now, for some odd reason, I'm also getting this error:
    g++.exe -o bin\Release\input_fill-in_struct.exe obj\Release\main.o -s
    obj\Release\main.o: file not recognized: File format not recognized
    collect2.exe: error: ld returned 1 exit status
    Process terminated with status 1 (0 minute(s), 0 second(s))
    0 error(s), 0 warning(s) (0 minute(s), 0 second(s))
    What header file is to_string() in?

  14. #29
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    First, laserlight showed you how to do it in post #16. Go back. Read it. Do not use std::getline to read an int.
    Second, you can look up where std::to_string resides by checking the documentation.
    Third, your command line should be g++ -std=c++11 (or c++14 or c++1y) my_source.cpp -o my_exe.exe
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #30
    Registered User
    Join Date
    Mar 2015
    Posts
    384
    I know what the command line has to show, but I don't know how to correct this on an IDE. If I knew how to program at the command line in Windows, and I knew the right command for fixing it, I would've done it, but sadly, I don't know either.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Chapter 13 Practice Problems
    By Osman Zakir in forum C++ Programming
    Replies: 43
    Last Post: 03-25-2015, 01:14 PM
  2. Chapter 5 Practice Problem #3
    By Tay in forum C++ Programming
    Replies: 3
    Last Post: 01-14-2015, 01:50 AM
  3. Chapter 15 - Practice Problem1
    By aresc in forum C++ Programming
    Replies: 2
    Last Post: 08-30-2013, 06:28 AM
  4. More Chapter 5 practice problems!
    By tsdad in forum C++ Programming
    Replies: 13
    Last Post: 05-17-2013, 11:06 AM
  5. Chapter 2 practice problems
    By Kyle Spalding in forum C++ Programming
    Replies: 14
    Last Post: 03-19-2013, 06:12 AM