There is an error in this line,
so that code does not compile. In fact z is never given any meaningful value, though it is used within the code.
There are also a number of warnings, which point to various areas which are definite or probable problems.
Here, the
==
operator is the relational operator to test for equality. I assume that you intended to use just
=
in order to assign the value, that is copy a character to
name[i]
That also gives rise to a problem.
name
is pointing to the literal string "Andrew Jona" which under the rules of C++ is a constant, that is, a read-only value. So you cannot modify it by assigning any value there.
But there is another problem.
surname
is a pointer. But what does it point to? It has not been initialised and therefore contains garbage. Hence you may neither read from nor write to anything at that address.
Another thing which looks wrong is that the for loops are nested three deep. That is there are three for loops, one inside the other. I don't think that makes sense. Keep the loops separate.
Also I don't think you should simply output the surname character by character,
cout<<surname[z];
- except perhaps during debugging.
Overall, this looks a bit of a mess, and not really well-thought out.
You need something like this:
1 2
|
char name[30] = "Andrew Jona";
char surname[30] = "";
|
Then you need to step through the name array until the space is found. That is the first loop. (Note, you may need to use a
break
statement to exit from this loop, or add the condition to the top of the for loop instead). Note, you could simply use
strchr()
instead of writing your own loop.
http://www.cplusplus.com/reference/cstring/strchr/
Add 1 to skip past the space.
Then copy characters one at a time from the name array to the surname array. That is the second loop. (Here you could just use
strcpy()
instead of writing your own loop).
http://www.cplusplus.com/reference/cstring/strcpy/
If necessary, add a terminating null character '\0' at the end of the surname.
Lastly print out the surname.