Programmer
Programmer

Reputation: 6753

The char array in C. How to find actual length of valid input?

Suppose i have array of characters. say char x[100]

Now, i take input from the user and store it in the char array. The user input is less than 100 characters. Now, if i want to do some operation on the valid values, how do i find how many valid values are there in the char array. Is there a C function or some way to find the actual length of valid values which will be less than 100 in this case.

Upvotes: 2

Views: 18888

Answers (4)

Abhishek Nag
Abhishek Nag

Reputation: 9

char ch;

int len;

while( (ch=getche() ) != '13' )

{

len++;

}

or use strlen after converting from char to string by %s

Upvotes: -1

Grega Kešpret
Grega Kešpret

Reputation: 12117

Yes, C has function strlen() (from string.h), which gives you number of characters in char array. How does it know this? By definition, every C "string" must end with the null character. If it does not, you have no way of knowing how long the string is or with other words, values of which memory locations of the array are actually "useful" and which are just some dump. Knowing this, sizeof(your_string) returns the size of the array (in bytes) and NOT length of the string.

Luckily, most C library string functions that create "strings" or read input and store it into a char array will automatically attach null character at the end to terminate the "string". Some do not (for example strncpy() ). Be sure to read their descriptions carefully.

Also, take notice that this means that the buffer supplied must be at least one character longer than the specified input length. So, in your case, you must actually supply char array of length 101 to read in 100 characters (the difference of one byte is for the null character).

Example usage:

#include <stdio.h>
#include <string.h>

int main(void)
{
    char *string = "Hello World";
    printf("%lu\n", (unsigned long)strlen(string));
    return 0;
}

strlen() is defined as:

size_t strlen(const char * str)
{
    const char *s;
    for (s = str; *s; ++s);
    return(s - str);
}

As you see, the end of a string is found by searching for the first null character in the array.

Upvotes: 10

Stuti
Stuti

Reputation: 1638

Every time you enter a string in array in ends with a null character. You just have to find where is the null character in array.

You can do this manually otherwise, strlen() will solve your problem.

Upvotes: 0

Billy ONeal
Billy ONeal

Reputation: 106609

That depends on entirely where you got the input. Most likely strlen will do the trick.

Upvotes: 1

Related Questions