My question is:
Is there a way to count the letters of a char array when it is input using cin.getline()
?
I tried using sizeof()
but it just give me the number i entered as size for the array.
My question is:
Is there a way to count the letters of a char array when it is input using cin.getline()
?
I tried using sizeof()
but it just give me the number i entered as size for the array.
If you use cin.getline()
you are reading characters into a buffer.
char buffer[100];
std::cin.getline(buffer, 100);
The actual number of characters read is retrievable from the stream.
std::size_t count = cin.gcount();
Note the line may be longer as this API will stop reading when the buffer is full (if this happens before end of line). So if you use this interface you may need to test the failbit
on the stream to make sure the whole line has been read.
char buffer[100];
std::cin.getline(buffer, 100);
if (std::cin.rdstate() & std::ios::failbit) {
std::cin.clear();
// Here just ignoreing the rest of the line.
// But you could read the rest of the data or something else.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Alternatively you can use std::getline()
and retrieve a string.
std::string line = std::getline(std::cin);
std::cout << line.size(); // The size is now part of the string.
This interface is much more intuitive.
It is preferred to use (std::string), but if you determined on using the char array, you can use strlen() in (c-string) library.
You can make a for loop on the arraylength after declaring the variable num_of_elements=0;
.
And in that loop add each counter number to the declared variable.
When the loop ends print that variable.