Reputation:
#include <stdio.h>
#include <string.h>
void separate(char s[20], char dummy[10], char* p){
strcpy(dummy, s);
for (int i = 0; i < strlen(dummy); i++){
if (dummy[i] == ' '){
dummy[i] = '\0';
}
}
*p = strchr(s, ' ');
p++;
}
int main(){
char s[10];
char dummy[10];
char l;
gets(s);
separate(s, dummy, &l);
puts(dummy);
puts(l);
}
I'm having trouble passing the last name to the main function as a string, the goal is to separate a string that consists of someone's first and last name.
Upvotes: 0
Views: 98
Reputation: 26315
Here is an example of using fgets
:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 20
#define NAMESTRLEN 10
void separate(char buffer[], char firstname[], char lastname[]);
int
main(void) {
char buffer[BUFFSIZE], firstname[NAMESTRLEN], lastname[NAMESTRLEN];
size_t slen;
printf("Enter first and last name: ");
if (fgets(buffer, BUFFSIZE, stdin) == NULL) {
printf("Error reading into buffer.\n");
exit(EXIT_FAILURE);
}
slen = strlen(buffer);
if (slen > 0) {
if (buffer[slen-1] == '\n') {
buffer[slen-1] = '\0';
} else {
printf("Exceeded buffer length: %d.\n", BUFFSIZE);
exit(EXIT_FAILURE);
}
}
if (!*buffer) {
printf("Nothing entered.\n");
exit(EXIT_FAILURE);
}
separate(buffer, firstname, lastname);
printf("Firstname = %s\n", firstname);
printf("Lastname = %s\n", lastname);
return 0;
}
void
separate(char buffer[], char firstname[], char lastname[]) {
int i;
char *last;
const char sep = ' ';
for (i = 0; buffer[i] != sep; i++) {
firstname[i] = buffer[i];
}
firstname[i] = '\0';
last = strchr(buffer, sep);
last++;
strcpy(lastname, last);
}
Upvotes: 0
Reputation:
#include <stdio.h>
#include <string.h>
void separate(char name[], char first[], char last[]){
strcpy(first, name);
for (int i = 0; i < strlen(first); i++){
if (first[i] == ' '){
first[i] = '\0';
}
}
char *p = strchr(name, ' ');
p++;
strcpy(last, p);
}
int main(){
char n[10], f[10], l[10];
gets(n);
separate(n, f, l);
puts(f);
puts(l);
}
I figured it out, thanks for the help anyway.
Upvotes: 1