The goal is to create substrings from an inputted string by extracting words which are separated by spaces.
The substrings have to be variables themselves.
Sounds easy, but what makes it hard is that you can only use strcpy, strcmp, strlen, strcat, strncpy, strncmp, strnlen, and strncat.
Example:
input:
"John 40 Hitman"
driver:
...
cout << word1 << endl
<< word2 << endl
<< word3 << endl;
output:
John
40
Hitman
Here is my code
#include <iostream>
#include <cstring>
#include <stdio.h>
int main(){
const char *string = "Name Age Job";
char name[10];
char age[10];
char job[10];
int length = strlen(string);
int temp = 0;
bool flag = false;
for(int i = 0; i < length + 1; i++){
if(isspace(string[i]) && !flag){
strncpy(name, string, i);
name[i] = '\0';
temp = i;
flag = !flag;
cout << name << endl;
continue;
}
if(isspace(string[i])){
strncpy(age, string + temp + 1, length - i - 1);
age[temp - i] = '\0';
temp = i;
cout << age << endl;
continue;
}
if(string[i] == '\0'){
strncpy(job, string + temp + 1, length);
job[temp - i] = '\0';
cout << job << endl;
}
}
It works but it has to use a flag boolean, strings are not dynamic, only works for a string with 2 spaces, and there is a lot of repeated code. Overall really janky, but I spent roughly two hours on this and I do not know how to improve it.
If you are wondering, this is indeed a homework problem, but it's an intro class and my professor only wants the correct output for a hard coded string with only 3 words. I, however, want to learn how to improve upon it and would be really grateful for any help. Thanks.