1

I'm not sure why this code does not work.

This code is supposed to, for example, switch all a's in the string to b's, and all b's to a's and print the result.

input:

abcd
a b
c d

Intended output:

badc

Code:

int main()
{
    int n, m, i, j;

    scanf("%d %d", &n, &m);

    char s[n+1], x[m+1], y[m+1];

    scanf("%s", s);

    for(i=0; i<m; i++)
    {
        scanf("%c", &x[i]);
        scanf("%c", &y[i]);
    }

    for(j = 0; j < m; j++)
    {
        for(i = 0; i<n; i++)
        {
            if(s[i] == x[j])
                s[i] = y[j];
            else if(s[i] == y[j])
                s[i] = x[j];
        }
    }

    printf("%s", s);

    return 0;
}
Hesham Saleh
  • 61
  • 2
  • 9

3 Answers3

1

Your logic is correct. You just need to put a space before %c specifier in both of the scanf

for(i=0; i<m; i++)
{
    scanf(" %c", &x[i]);
    scanf(" %c", &y[i]);
}

and it will work. This is because the \n leftover by the previous scanf is read by second scanf and same is happening for the space in between the the input characters a b and c d. A space before %c in scanf will consume all white-spaces.

You can change loop to replace characters in only one iteration

for(i = 0; i < n; i++)
{
    for(j = 0; j < m; j++)
    {
        if(s[i] == x[j])
        {
            s[i] = y[j];
            break;
        }
        if(s[i] == y[j])
        {
            s[i] = x[j];
            break;
        }
    }
}
haccks
  • 104,019
  • 25
  • 176
  • 264
  • How do I reduce the time limit of this program? – Hesham Saleh Oct 28 '15 at 18:03
  • @haccks is there an execution time penalty for the redundant `else`? – Weather Vane Oct 28 '15 at 18:16
  • @WeatherVane; `else` is not redundant but more comparisons will take more time assuming `m` has some big value. – haccks Oct 28 '15 at 18:19
  • 1
    @haccks the `else` is redundant because of the preceding `break` when the previous condition was true. – Weather Vane Oct 28 '15 at 18:20
  • @WeatherVane; Ummm....... if previous is not true then `else` part will execute. But, you are right. `else` is redundant, but there is no execution time penalty. Modern compilers are smart enough to optimize it. – haccks Oct 28 '15 at 18:24
1

As I commented you need a space before the %c in these lines

scanf("%c", &x[i]);
scanf("%c", &y[i]);

to prevent the %c format type reading the white-space left in the input buffer by previous scanf calls. Change to

scanf(" %c", &x[i]);
scanf(" %c", &y[i]);
Weather Vane
  • 33,872
  • 7
  • 36
  • 56
0

In addition to https://stackoverflow.com/a/33397902/2410359

Code does not insure that s is null character terminated at print time - leads to undefined behavior. Should use for(i = 0; s[i] && i<n; i++) to prevent overwriting it.

This may account for excessive time usage.


OP posts below as input. Certainly 2 numbers must precede that for scanf("%d %d", &n, &m);

abcd
a b
c d
Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256