I am trying to have my program take a name as input from the user and then print out the initials of that name. ie tommy brown --> tb
What I have so far is this:
int main (void)
{
char scroll[100] = {"kang cheng junga"};
printf ("%c\n", *(scroll+2));
for (int i=0; i<100; i++)
{
if (*(scroll+i)=" ")
{
printf (*(scroll+i+1));
}
}
I keep getting this error:
error: incompatible pointer to integer conversion assigning to 'char' from 'char [2]'
[-Werror,-Wint-conversion] if (*(scroll+i)=" ")
error: using the result of an assignment as a condition without parentheses
[-Werror,-Wparentheses] if (*(scroll+i)=" ")
Can anyone tell me how I've screwed this up? I am having a hard time understanding how * and & function in a C. I am a beginner so I don't really know what I'm doing.
In addition to strtok
, this is one time you can also make use of strpbrk
to easily find each space
:
#include <stdio.h>
#include <string.h>
int main (void) {
char scroll[100] = "kang cheng junga";
char *p = scroll;
printf ("\n full name: %s\n", scroll);
printf (" initials : %c", *p);
while ((p = strpbrk (p, " ")))
printf ("%c", *++p);
printf ("\n\n");
return 0;
}
Output
$ ./bin/initials
full name: kang cheng junga
initials : kcj
You can also eliminate the dependence on string.h
with an alternative version that uses pointers alone:
#include <stdio.h>
int main (void) {
char scroll[100] = "kang cheng junga";
char *p = scroll;
printf ("\n full name: %s\n", scroll);
printf (" initials : %c", *p);
while (*p++)
if (*p == ' ' && *++p)
printf ("%c", *p);
printf ("\n\n");
return 0;
}
The Error you are getting is because of the assignment operator (=) .
if (*(scroll+i)=" ")// assigning a value(blank)
{
printf (*(scroll+i+1));
}
if (*(scroll+i) == ' ')//Comparing it with a value (blank)
{
printf (*(scroll+i+1));
}
In C, =
is assignment operator, and ==
is equality operator. You need to use the later one.
That said, there is a nice library function, named strtok()
which can make your life easier. Just pass the string and a delimiter, (here, the space) and it will return the token to you, for which you can print the first character to get the initials.
along with strtok or strchr here is a simple way to implement , some boundary conditions are missing like name ending with single letter etc
#include <stdio.h>
int main (void)
{
int i = 0;
char scroll[100] = {"kang cheng junga"};
char *p = scroll; // point to base
printf("%c", *p ); // first letter is almost always certain
while( *p != '\0' ) { // till end of String
if ( *(p-1) == ' ' && *(p+1) != '\0') { // If previous is space and next letter exists
printf("%c", *p ); // take it save it or print it
}
p ++ ; //proceed
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.