Outputting Character Array. Help please?

Hello,

My program takes the firstName and lastName c_string null terminated arrays and combines them into the fullName array. The fullName array is sent to the displayInfo function where it will be outputted to the screen.

When it compiles, the 20 iterations of the for loop print out the first and last names but leaves a bunch of empty space after which i am assuming to be the unused array elements.

How do I get the for loop to stop, after reading the last character of the last name.

Thank you

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  #include <iostream>
#include <cstring>
using namespace std;

void displayInfo(char fullName[], int age);

int main()
{
	char firstName[10] = "Name";
	char lastName[10] = {'\0'};
	char fullName[20] = {'\0'};
	int age;

	cout << "Enter your age: ";
	cin >> age;
	cout << "Enter your last name: ";
	cin >> lastName;

	strcpy(fullName, firstName);
	strcat(fullName, " ");
	strcat(fullName, lastName);

	displayInfo(fullName, 20);

return 0;
}

void displayInfo(char fullName[], int age)
{
	cout << "Hello ";
	for (int i = 0; i < 20; i++)
	{
		cout << fullName[i];
	}

	cout << "." << " You are " << age << " years old.\n\n";
}
use strlen( fullName ) in place of 20
or even
for( /*int*/size_t i = 0; fullname[i]; i++ ) { }
Last edited on
Topic archived. No new replies allowed.