#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;}
#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;
}
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 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.
#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;
}