0

How can I copy a char to an array?

char s[100], p[100];
in = fopen("infix.in","r");

while (fscanf(in,"%s",s) != EOF) {
    for (j = 0; j < strlen(s); j++) {
        if (s[j] - 48 >= 0 && s[j] - 48 <= 9) {
            for (i = j; i < j + 1; i++) {
                strcpy(p[i],s[j]);
            }
        }
    }
}

turbo c said "Cannot convert 'int' to 'char*' "

This is not working. How do I solve this?

3 Answers3

0

I'm not sure what you want to achieve, but it seems you want to copy all digits from s to p. If that's the case, you need to know that strcpy takes pointers as parameters, not chars (so, as you wrote, it should have been strcpy(p+i, s+j)) and it copies the entire string, until the nul character (basically, all that is displayed by printf(%s, s)). To copy a character, just use the assignment operator: p[i] = s[j].

Paul92
  • 8,827
  • 1
  • 23
  • 37
0

To copy one array element to another location, you can just assign it

p[i] = s[j];

Your loop goes from j to j + 1, copying just one element. This means, you can eliminate the inner for loop entirely

p[j] = s[j];

The test for a digit can be done with

if (isdigit(s[j]))
    p[j] = s[j];

You can also save the string length in a variable, to avoid the expensive computation. The entire loop becomes

int len = strlen(s);
for (j = 0; j < len; j++) {
    if (isdigit(s[j]))
        p[j] = s[j];
}

p[i] = 0;

But, it looks like you want to extract the digits, which would involve an additional index for the target array

int len = strlen(s);
int i = 0;
for (j = 0; j < len; j++) {
    if (isdigit(s[j])) {
        p[i] = s[j];
        ++i;
    }
}

p[i] = 0;
Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
-1

I suggest using strncpy which eliminates the need to loop and provides the required functionality out of the box.

strncpy(s,p,strlen(s);

Correction: the strcpy is unnecessary and should be replaced with an assign.

I also suggest replacing fscanf with fgets. There really is no need for fscanf here.

  • `p` is currently indeterminate, copying from it isn't a good idea. And strncpy doesn't null-terminate its buffer sometimes , so it is a poor choice for this operation. – M.M Apr 20 '14 at 15:03
  • My mistake, I was referencing the inner for loop but as others have pointed out it only needs to be a simple assign. – Michelle de Haan Apr 23 '14 at 17:36