Name program

I am supposed to write a code that instructs you to input your name. You then receive a response Your first name is, Your last name is.

Example
Input your name

john doe

Your first name is john
Your last name is doe

I can not figure out how to split strings so that I can have the last name show. The code below is my frustrated failed attempt after hours.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include "stdafx.h"

#include <string.h>

int main(void)

{char fname[20], lname[20], name[40];

int i;

printf("input your name\n");

gets(name);
for (int i=0; i<=strlen("fname"); i++)
	if (lname[i] == ' ')

         printf("%c\n",lname[i]);
printf("Your first name is");
puts(fname);

printf("Your last name is");
puts(lname);

return 0;}
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
#include <stdio.h>
#include <string.h>

int main(void)

{
	char fname[20] = {'\0'}, lname[20] = {'\0'}, name[40] = {'\0'};
	int index = 0;	

	printf("input your name: ");
	gets(name);
	
	for (int i = 0; i < strlen(name); i++)
		if (name[i] == ' ')
			index = i;

	strncpy(fname, name, index);
	strncpy(lname, name + index + 1,  strlen(name) - strlen(fname));
		
	printf("\nYour first name is %s", fname);
	printf("\nYour last name is %s", lname);
	getchar();

	return 0;
}
Last edited on
Is this a c program? Kind of looks like it. But anyways the easiest solution in c++ would be this

1
2
3
4
5
6
7
8
9
10
11
12
13

#include <iostream>
#include <string>

int main()
{
    std::string first , last;
    std::cout << "Please enter your firstname lastname( space separator): ";
    std::cin >> first >> last;
    std::cout << "Your first name is : " << first << std::endl;
    std::cout < "Your last name is : " << last << std::endl;
    return( 0 );
}
Thank you for your reply, however the program is supposed to be written using gets_s and puts.
Thank you again Yanson for your help. The strncpy makes more sense after seeing it laid out that way than it did in the book. I tweaked it around to make it acceptable for the assignment. The new version is below.


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
 #include "stdafx.h"

#include <string.h>

int main(void)

{
	char fname[20]= {'\0'}, lname[20]= {'\0'}, name[40]= {'\0'};
	int index = 0;

	puts("input your name\n");
	gets(name);

	for (int i=0; i<strlen(name); i++)
		if (name[i] == ' ')
			index=i;

	strncpy(fname, name, index);
	strncpy(lname, name + index + 1,  strlen(name) - strlen(fname));

	printf("Your first name is ");
	puts(fname);

	printf("Your last name is ");
	puts(lname);

	return 0;
}
Topic archived. No new replies allowed.