Search code examples
c++arraysstringdynamic-memory-allocation

how can I limit a user to input 8 characters into string(dynamic char array)in c++?


int size;
cout<<"enter string size"<<endl;
cin>>size;
char * string1 = new char[size];

well hello,im working on a project and one of my functions purpose is to get a dynamic char array as arg which sends to the output the first letters of the words in the string. so the user decides the string length (for the initialized dynamic array), but then how can i ensure he won't exceed the length of the array he chose?(the compiler does not Refer to it as a mistake). can i force the 'cin' operator to limit itself?


Solution

  • Using std::string is better, but...

    char input [8];
    cin.getline (input, 8);
    

    Note, there may still be data in the input buffer after this that you may need to deal with.

    Edit

    Given the original code in the question:

    cin.getline(string1, size);