2017-04-04 74 views
0

我试图解决的问题交换元素时是:获得错误的输出数组

考虑字符数组。从左侧和右侧开始扫描每个字符一个 一个。如果两个扫描字符都是 字母表,则将它们交换到阵列中。

实施例:

如果阵列是! w , s t u # p a b然后我将从 开始扫描的左和右。即首先我会扫描!b因为都是 不是字母我不会交换。然后我将移动到wa,因为 都是字母,我会交换它们。我会继续这个过程直到 我到达阵列的中间。

我的代码:

#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 

为什么会出现错误的输出?错误在哪里?

+0

你为什么不只是读字符串作为'的scanf(“%S”,S);' – Sajin

+0

我试过了,注意变化 – Arvindsinc2

+1

而读它你没有空终止字符串。打印它;它会与你期望的不同。 –

回答

1
#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; 
} 
+0

** **怎么解释什么是错的(因此_replying_答案)? – linuxfan