c - 交换数组中的元素时出现错误输出

标签 c arrays

The Problem I am trying to solve is:

Consider an array of characters. start scanning each character one by one from both left and right. If both the scanned characters is an alphabet then swap them in the array.

Example:

If the array is ! w , s t u # p a b then I will start scanning from both left and right. ie first I will scan ! and b since both are not alphabets I will not swap. Then I will move to w and a , since both are alphabets I will swap them. I will continue this process till i reach the middle of the array.

我的代码:

#include <stdio.h>
#include <ctype.h>

int main() {

    int p,q,len,i;
    char s[100],temp;

    //ask the length of string
    printf("Enter the number of chars:\n");
    scanf("%d",&len);

    //get each char in the string and store in array s[]
    printf("Enter %d chars:\n",len);
    for(i=0;i<len;i++)
        scanf("%c",&s[i]);

    //start scanning char by char from both sides
    p=0;
    q=len-1;

    while(p<=q)
    {
        // swap chars if both p and q points to a letter
        if(isalpha(s[p]) && isalpha(s[q]))
        {
        temp=s[p];
        s[p]=s[q];
        s[q]=temp;
        }
        //increment p to move towards right
        p++;
        //decrement q to move towards left
        q--;
    }

    //print all chars in the array
    for(i=0;i<len;i++)
        printf("%c",s[i]);

    return 0;
}

我的输入:

10
!w,stu#pab

我的预期输出:

!a,sut#pwb

我得到的输出:

!w,tsu#pa

为什么我得到错误的输出?错误在哪里?

最佳答案

#include <stdio.h>
#include <ctype.h>

int main() {

    int p,q,len,i;
    char s[100],temp;

    //ask the length of string
    printf("Enter the number of chars:\n");
    scanf("%d",&len);

    //get each char in the string and store in array s[]
    printf("Enter %d chars:\n",len);
    scanf("%s",&s[i]);

    //start scanning char by char from both sides
    p=0;
    q=len-1;

    while(p<=q) {
        // swap chars if both p and q points to a letter
        if(isalpha(s[p]) && isalpha(s[q])) {
            temp=s[p];
            s[p]=s[q];
            s[q]=temp;
        }
        //increment p to move towards right
        p++;
        //decrement q to move towards left
        q--;
    }

    //print all chars in the array
    for(i=0;i<len;i++)
        printf("%c",s[i]);
    return 0;
}

关于c - 交换数组中的元素时出现错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198377/

相关文章:

php - 获取数组的字符串

c - 将字符串数组分配和检索给 void 指针

c - 错误 : expected expression before 'student'

c - 在 C 中创建动态矩阵的方法?

python - 从 C 到 Python 的回溯排列

c++ - 位检查验证

javascript - 如何在 JS 表中选择元素?

arrays - Mongoose 查询,查找 B.array 中与 A.array 中匹配的所有 B 类型项目

java - 二维数组但带有索引 - java

c - linux同进程下的线程如何分配stack或内存