c++iostream

How to get the size of input from console using c++?


How would you get the size input string from console or the size of valid characters in the buffer?

char buffer[100];
cin >> buffer;

I'm looking to put the \0 where the input ends.


Solution

  • The question is moot. When the user types more than 100 characters, you have a buffer overrun. You may crash. If not, you got a security issue at best. You shouldn't do this. Read the input a character at a time, or use a safer string library. gets_s comes to mind if it's supported on your platform.

    But in answer to your question, this might be what you need:

    char buffer[100] = {}; // zero-init the entire array
    int length = 0;
    cin >> buffer;
    length = strlen(buffer); // length is the length of the string