Copy part of a string

So I want to copy characters from a string into a second string until there is a space.
For example, the first string would say "Hello World" and after the loop the second string would say "Hello".
This is what I have tried so far, but when I compile it it gives me the error "error: ISO C++ forbids comparison between pointer and integer [-fpermissive]"
1
2
3
4
5
6
char input[50], keyword[50];

for(int i = 0; input[i] != " "; i++)
       {
           keyword[i] = input[i];
       }


The error is on the line with the for loop.
If anyone knows what the problem is and how to fix it, or a different way of doing this it would be much appreciated.
input[i] is a character
" " is a string of characters.
That's why they can't be compared, they are of differing types.

Use this input[i] != ' ' - notice single quotes, not double.
Alright, thanks. It's compiling now, but when I run it a window pops up that says the program has stopped working. However it's just a standard Windows warning and gives no particular error. I'll post the full code, if someone could point out what I've done wrong I would be appreciative.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main()
{
    char input[50], keyword[50];

    cin >> input;

    for(int i = 0; input[i] != ' '; i++)
        {
            keyword[i] = input[i];
        }

    cout << input << " " << keyword;


    }
}
Just to be sure, are you aware that with this code your input is limited to 49 characters and must contain a space ?

Apart from that, I think the problemis due to the fact you forgot to put a '\0' character at the end of "keyword".
A c-string needs to have a terminating null character. After copying the letters belonging to the word, set the next character to zero.

In addition, cin >> input; will stop at the first space. Therefore the for loop will never find the space as there isn't one.

Use getline instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main()
{
    char input[50], keyword[50];

    cin.getline(input,50);

    int i;

    for (i = 0; input[i] != ' ' && input[i] != 0; i++)
    {
        keyword[i] = input[i];
    }
    
    keyword[i] = 0; // Add null terminating byte

    cout << input << " " << keyword;
}
Last edited on
Thank you so much. For some reason at school I never had to put a null terminator at the end. In fact I don't even think they were discussed. Anyway, thanks again.
Topic archived. No new replies allowed.