Home > Blockchain >  Trying to print a sring,but getting "@@" in place of data
Trying to print a sring,but getting "@@" in place of data

Time:02-27

I am trying to get a string from the user, then remove all characters in a string, except the alphabets. The string a string containing whitespace. I have input a string, but the output is only "@@".

I don't know what's happening.

//C program
//Program to remove all characters in a string, except alphabet
#include <stdio.h>
#include <string.h>
int main()
{
char str[150], copy[150];
int i = 0, j = 0;
printf("\nEnter a string : ");
fgets(str,150,stdin);
for (i = 0; i < 150; i  )
{
    if ((str[i] >= 'a' && str[i] <= 'z') || 
    (str[i] >= 'A' && str[i] <= 'Z') || (str[i] == '\0') )
    {
        *(copy   j) == *(str i);
        j  ;
    }
}

printf("\nResultant String : ");
for (int i = 0; i < strlen(str); i  )
{
    printf("%c",copy[i]);
}
printf("\n");
return 0;
}

On terminal this is the program being run, I input "1 2 3 4 get on the dance floor".

Enter a string : 1 2 3 4 get on the dance floor

Resultant String : @@

CodePudding user response:

The main problem is you're not doing an assignment here:

*(copy   j) == *(str i);

The == is for comparison. You want =:

*(copy   j) = *(str i);

Your loop conditions are also incorrect:

for (i = 0; i < 150; i  )

...

for (int i = 0; i < strlen(str); i  )

For the first loop, you're reading all bytes in the source array instead of just the ones that were set, and in the second one you're using the length of the source string instead of the result string to print the result. These should be:

for (i = 0; i < strlen(str); i  )

...

for (int i = 0; i < strlen(copy); i  )
  • Related