This code should ask the user for a their name and then split it at the space.
It should put the firstname in the variable first, and the last name in de variable lastname
#include <iostream>
using namespace std;
int main()
{
char string[80];
char first[20];
char lastname[20];
bool f = true;
int c = 0;
cout << "Whats your Name? \n";
gets(string);
for(int i =0; i < strlen(string); i++){
if(string[i] == ' ') {
f = false;
c = 0;
}
if(f) {
first[c] = string[i];
} else if(!f) {
lastname[c] = string[i];
}
c++;
}
for(int i = 0; i < strlen(first); i++) {
cout << first[i] << "\n";
}
for(int i = 0; i < strlen(lastname); i++) {
cout << lastname[i]<< "\n";
}
return 0;
}
Unless you really need to write this using only C functions, it would be much easier to use C++ strings.
Something like (this is untested):
This means you don’t have to worry about null-terminating strings or string lengths or anything like that. As flolo said, your code doesn’t do that and thus will definitely run into problems. The memory layout of a C string is an array of characters with a null byte on the end, which is how things like strlen() know where the end of the string is. Also, your code’s going to have a horrible time the moment somebody enters a name with more than 20 characters in it, which isn’t particularly implausible.