Getting the Array size

Hi I am currently reading characters into an array which I set the size as 50...but I am doing it from input so the characters inputted may not always be 50..so when I do the for loop to display each character how do I get the size of the input so I do not display the entire array and just display what was inputed. Thanks alot for the help
You could initialise the array to '\0' first then parse through the characters, checking to see if they're '\0' or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const int ARR_SIZE = 50;

char my_string[ARR_SIZE];
int count = 0;

for (int i=0; i < ARR_SIZE; i++)
{
   my_string[i] = '\0';
}

cin >> my_string;

for (int j=0; j<ARR_SIZE; j++)
{
   if (my_string[j] != '\0')
   {
      count++;
   }
}

cout << "String is " << my_string << " and is " << count << " characters long" << endl;


Ultimately, though, it's easier to avoid all this by using the string class. You could then just find out the length by using the length function:

1
2
3
4
5
string my_string;

// Get input etc

cout << "Length: " << my_string.length();


EDIT: Altered NULL to '\0' as per Grey Wolf's advice.
Last edited on
closed account (z05DSL3A)
iHutch105 wrote:
You could initialise the array to NULL first then parse through the characters, checking to see if they're NULL or not.
You should not use NULL, it should be '\0'.

1
2
3
4
for (int i=0; i < ARR_SIZE; i++)
{
   my_string[i] = '\0';
}


@Grey Wolf - I could be overlooking something obvious, but care to divulge why?
closed account (z05DSL3A)
NULL is an implementation-defined macro for a null pointer constant, it is not meant to be used as a null character. Although it may 'work out in the end' it is not what you should be doing and not what you should encouraging others to do.

Theoretically a compiler manufacturer could now define NULL to be nullptr (unlikely as to many people misuse NULL)
I see. Cheers. I'll edit the original suggestion.
Always end a character string with a zero (0). If you enter character into a string through your keyboard when you press enter the last character will be zero. Therefor a character string is defined as szString. s stand for string and z stand for terminated by zero. Unsigned character strings normally do not get terminated by a zero because a zero is a valid unsigned character.
Zero = 0. Not ascii '0'.
Last edited on
Here is an example that will end a character string wit zero (0) or ('\0'). Which are the same.

char szBuffer[20];
int iCnt;

// Copy My Sting into buffer and end with zero
strcpy(szBuffer, "My String");

// Count characters until zero
for(iCnt = 0; szBuffer[iCnt] != 0; iCnt++){}

// Print out
cout << "String is " << szBuffer << " and is " << iCnt << " characters long" << endl;
Last edited on
Topic archived. No new replies allowed.