scanf()方法在while循环中不起作用?

问题描述 投票:-1回答:2

我已经离开这个循环了5个小时。我的scanf方法不起作用。 这是我的循环。 我无法执行库的strcmp所以我自己写了。

int string_compare(char str1[], char str2[])//Compare method
{    
    int ctr=strlen(str1);
    int ctr2=strlen(str2);
    int counter=0;
    if(strlen(str1)!=strlen(str2) ){//if their lengths not equal -1     
        return -1;
    } else
    {
        for (int i = 0; i < strlen(str1); ++i)
        {
            if(str1[i]==str2[i]){ //looking for their chars
                counter++;
            }
        }

        if(counter==strlen(str1)){  
            return 0;
        } else
        {
            return -1;
        }
    }
}

char str1[100]; //for users command
char newString[10][10]; //after spliting command i have

while(string_compare(newString[0],"QUIT") != 0){
    printf("Enter Commands For Execution\n");
    scanf("%10[0-9a-zA-Z ]s\n",str1);
    int i,j,ctr;
    j=0; ctr=0;
    for(i=0;i<=(strlen(str1));i++)
    {
        // if space or NULL found, assign NULL into newString[ctr]
        if(str1[i]==' '||str1[i]=='\0')
        {
            newString[ctr][j]='\0';
            ctr++;  //for next word
            j=0;    //for next word, init index to 0
        } else
        {
            newString[ctr][j]=str1[i];
            j++;
        }
    }

    if(string_compare(newString[0],"QUIT") == 0){
        printf("Quitting\n");
        break;
    }

    if(string_compare(newString[0],"MRCT") == 0){
        printf("hey\n");
    }
    if(string_compare(newString[0],"DISP") == 0){
        printf("hey2\n");
    }
}

当我执行我的c文件时, 循环要求我输入诸如“MRCT”之类的命令。

它永远打印

Enter Command
hey
Enter Command
hey

我使用scanf()的方式在这里不起作用。

c loops scanf
2个回答
-1
投票

使用:scanf("%[^\n]\n" , str1);使用scanf函数得到一条线。


1
投票

scanf()在第一次失败后停止扫描。

所以在这里:

scanf("%10[0-9a-zA-Z ]s\n",str1);

扫描试图解释三件事:

  • 一个字符串%[]变成一个变量str1
  • 人物s
  • 字符'\ n'将导致从输入中读取一系列空格字符。

请注意,如果字符串为零长度,它将在字符串处失败,而不会解释s\n字符。

一:我怀疑s是一个错误,你不想要它。

二:不要使用"%[^\n]\n"读取一行。如果该行为空(仅具有\n字符),则会失败。

if (scanf("%10[0-9a-zA-Z ]", str1) == 1)
{
    // Always check that the value was read.
    // Then deal with it.
    ....
}
scanf("%*[^\n]"); // Ignore any remaining character above 10.
                  // Note this may still fail so don't add \n on the end
                  // Deal with end of line separately.

char c;
if (scanf("%c", &c) == 1 && c == '\n')  // Now read the end of line character.
{
    // End of line correctly read.
}
© www.soinside.com 2019 - 2024. All rights reserved.