Search code examples
c++arraysc-stringscin

How do I get the size of a c-string input in cin?


So, basically I want to write a program in c++ that encrypts text by moving the chars by a random number in the ascii table. But first I need to get a string by the user. When I want to store the c-string in a char array my problem is that I first need to know the size of the string to have the right size in the array. How can I get it without needing to know the future? Thanks in advance!


Solution

  • Below are two simple approaches to solving this problem you have.
    You can choose one of them based on the needs of your program.

    Here:

    #include <iostream>
    #include <string>
    
    #define METHOD_NUM 1 // set this to 1 for the 1st approach
                         // or 2 for the 2nd approach
    
    int main( )
    {
        // an arbitrary size, I chose 20 for demo
        constexpr std::size_t requiredCharsCount { 20 };
    
    #if METHOD_NUM == 1
    
        std::string user_input { };
        std::size_t buffSize { };
    
        do
        {
            std::getline( std::cin, user_input );
    
            // number of chars in the user input
            buffSize = user_input.size( );
    
        } while ( buffSize > requiredCharsCount );
    
    #else
    
        // + 1 is for the '\0' aka the null terminator
        constexpr std::size_t buffSize { requiredCharsCount + 1 };
        
        std::string user_input( buffSize, '\0' );
        std::cin.getline( user_input.data( ),
                          static_cast<std::streamsize>( user_input.size( ) ) );
    
    #endif
    
        std::cout << "The user entered: " << user_input
                  << '\n';
    
        // manipulate the string however you want
        // just make sure that the indices you're using are
        // less than buffSize to avoid buffer overrun
        user_input[0] = '1';
        user_input[5] = 'g';
        user_input[2] = '@';
    }
    

    To begin with, I recommend you use the std::string class because it handles all the necessary allocations/deallocations for you and automatically keeps track of that stuff. A C-style array or even a std::array won't have this kind of luxury out of the box.

    Now, the 1st approach lets the user enter as many characters as they want, and then the program checks the number of characters entered to make sure it's not greater than a predefined number (i.e. requiredCharsCount and I have set it to 20). If it is, then the program will ask for new input. In case you don't want to set a limit for the user you can remove that variable and the do-while loop.

    Speaking of the 2nd approach, as you can see, it lets the user enter a limited number of characters (again, 20) and won't read more than the limit even if the user's string contains more than that. This approach is more efficient but obviously has the limitation that I just mentioned.