I have two strings, one with an email address, and the other is empty.
If the email adress is e.g. "abc123@gmail.com", I need to pass the start of the email address, just before the @ into the second string. For example:
first string: "abc123@gmail.com"
second string: "abc123"
I’ve written a loop, but it doesn’t work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char email[256] = "abc123@gmail.com";
char temp[256];
int i = 0;
while (email[i] != '@')
{
temp = strcat(temp, email[i]);
i++;
}
printf ("%s\n", temp);
system ("PAUSE");
return 0;
}
Basically, I took every time one char from the email address, and added it into the new string. For example if the new string has a on it, now I’ll put b with it too using strcat….
Pointers. Firstly, strcat() returns a char pointer, which C can’t cast as a char array for some reason (which I hear all C programmers must know). Secondly, the second argument to strcat() is supposed to be a char pointer, not a char.
Replacing
temp = strcat(temp, email[i]);withtemp[i] = email[i];should do the trick.Also, after the loop ends, terminate the string with a null character.
(After the loop ends,
iis equal to the length of your extracted string, sotemp[i]is where the terminal should go.)