试图运行程序第二部分的两部分不能输入字符串

时间:2012-03-26 18:04:56

标签: c

我试图让这个程序的两个部分都能正常工作,因为你可以看到我已将它与第一部分(问题1)和第二部分(问题2)分开。问题是第一部分运行正常,当第二部分开始时我无法输入任何字符串,它似乎只是跳过代码而不让我输入字符串。

如果删除程序的第一部分(问题1),那么一切正常,我可以输入字符串。什么因素导致了这个问题。

int main()
    {
        first();
        second();

    }

//Question 1

int first()
{
/* dataarray.c */
float data[20] = {
  50.972438, 93.765053, 9.252207, 1.851414, 16.717533,
  71.583113, 97.377304, 20.352015, 56.309875, 0.072826,
  23.986237, 36.685959, 80.911919, 86.621851, 53.453706,
  96.443735, 29.845786, 18.119300, 31.079443, 52.197715 };

/* The number of elements in the data array */
int data_size = 20;
int pos;
int j;
int i;
int k;

    printf("Question 1\n");

for(i=0;i<data_size;i++)
{
    printf("\nArray %i is %f ",i,data[i]);    //Initial arrays print statement
}
    printf("\n\nArray number to delete:");   //User Choose one to delete
    scanf("%i",&pos);

k =0;
for(j = 0; j< pos;j++) 
{
    printf("\n Array %i is now %f ",k,data[j]); 
    k++;
}

k=pos;
for(j=pos+1;j<data_size;j++) 
{
    printf("\n Array %i is now to %f ",k,data[j]); //Shows array changed to
    k++;
}
data_size = data_size - 1;  //Decreases data size
}

//Question 2

int second()
{
    printf("\n\nQuestion 2\n");

int a,b,check=0;
char str[20];
     printf("\nEnter a String:\n"); //User inputs word to check if its palindrome
gets(str);

for(b=0;str[b]!=0;b++); //Starts at 0 increment till the last length
b=b-1;
a=0;
while(a<=b)
{
    if(str[a]==str[b]) //String a is forwards b is backwards
    {
        a=a+1;
        b=b-1;
        check=1; //If check = 1 then a palindrome
    }
    else
    {
        check=0; //If check = 0 then it not a plaindrome
        break; //Loop break
    }

}

if(check==1)
    printf("It is a Palindrome:"); //Statement printed if check = 1
else
    printf("It is not a Palindrome\n"); // Else if 0 this statement is printed

}

1 个答案:

答案 0 :(得分:1)

当您在第一部分中调用scanf时,我假设您输入一个后跟换行符的数字。 scanf使用该数字,但换行符保留在缓冲区中。然后,第2部分中的gets()会看到换行符并返回一个空行。一个简单的解决方案就是

scanf( "%i\n", &pos );

BTW,从不使用获取。改为使用fgets。