nszejna
nszejna

Reputation: 95

How do I fill an array with characters from user input, while counting how many array indexes have been used? (using cin.get)

I need to use the get function and count how many indexes have been filled I have been running into a couple problems.

It seems that using cin.get in this way only allows me to fill the array and doesn't allow me to count how many variables in the array have been filled:

#include <iostream>

int main()
{
   char line[25];
   cout << " Type a line terminated by enter\n>";
   cin.get( line, 25 );

}

I have a feeling that I need to use a for loop such as the one below, but the problem with this is it doe not end with enter, the user has to fill the whole array and I need to be able to enter any amount of characters under the limit. Also the example did not use sentinel value, so though it would seem to solve this, it doesn't seem to be the solution.

void fill_array(char array[], int max_count, int& num_used)
{
    char input;
    int index = 0;

    cout << "Enter a text string to test" << endl;
    for( index = 0;index < max_count; index++)
    {
         cin.get(input);
         array[index] = input;
         num_used++;
    }
}

Upvotes: 1

Views: 2881

Answers (1)

v154c1
v154c1

Reputation: 1698

You can use gcount to get the number of characters read byt the last unformatted operation, like cin.get.

char line[25];
cout << " Type a line terminated by enter\n>";
cin.get( line, 25 );
std::streamsize read_chars = cin.gcount();

Upvotes: 2

Related Questions