【问题标题】:While loop, when it operates with "string" data, How to abort it with a specific word or letter?While循环,当它对“字符串”数据进行操作时,如何用特定的单词或字母中止它?
【发布时间】:2018-03-20 13:30:58
【问题描述】:

我只是一个初学者,所以请不要过分评判。 我试图理解,当它使用字符串时,我如何停止一个while循环?当它只是数字时,很容易将它与任何非数字符号或任何特定数字(如 0)绑定;但是如果它是一个字符串,它就不同了。请帮助我理解。 所以下面是一个简单的代码。起初我尝试使用一些字符作为评估,例如

while(name1!='q'){
}

但它不起作用。 然后我用一个特定的字符串写了一个额外的数组,并进行了比较:

char abort_name[4]={"stop"};
 short abort=strcmp(name1,abort_name);
    while (abort!=0) {

看看我的代码。我知道它可能不起作用,因为在任何字符串的末尾都有这个未打印的 \0 符号,并且因为我正在比较 2 个数组,一个有 10 个符号,另一个只有 4 个,但是我怎样才能绕过它呢?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
    char name1[10];
    char abort_name[4]={"stop"}; //I'm trying to use a cancelling word, but it doesn't work

    printf("enter you name here /stop - to cancel/:   ");

    int check1=scanf("%s", name1);
    short abort=strcmp(name1,abort_name);
    while (abort!=0) {
        printf("value is: %d\r\n", check1);
        printf("\r\nname is: %s", name1);
        printf("\r\n\r\nenter you name here:   ");
        short check1=scanf("%s", name1);
        short abort=strcmp(name1,abort_name);

    }

    return 0;
}

更新: 现在我发现了错误,谢谢大家的解释!

【问题讨论】:

    标签: c arrays string while-loop


    【解决方案1】:
     while (abort!=0)
     {
       ...
       short abort=strcmp(name1,abort_name);
     }
    

    您正在遮蔽main 例程中定义在while 语句上方的abort 变量:它们是两个独立的变量,因此您的条件永远不会改变。

    将其更改为:

    abort=strcmp(name1,abort_name);
    

    分配主要的abort 变量。

    (注意check1也有同样的问题)

    还要注意:

    char abort_name[4]={"stop"};
    

    定义了一个由 4 个字符串组成的 array。不是你想要的,你需要的:

    const char abort_name[]="stop";
    

    const char *abort_name="stop";
    

    (顺便说一句,让编译器为你计算大小,4 是不够的,因为 nul-terminator)

    【讨论】:

      【解决方案2】:

      考虑使用 fgets 作为输入并使用 do/while 循环进行迭代,直到输入 quit

      #include <stdio.h>
      #include <string.h>
      #include <stdlib.h>
      
      int main(void) {
          char name1[100];
          int match = 0;
      
          do {
              printf("enter you name here ( or quit):   ");
              fflush ( stdout);//printf has no \n
              if ( fgets ( name1, sizeof name1, stdin)) {//get a line
                  if ( 0 != ( match = strcmp ( name1, "quit\n"))) {//compare to quit\n
                      printf("\r\nname is: %s", name1);
                  }
              }
              else {
                  fprintf ( stderr, "fgets problem\n");
                  return 0;
              }
          } while ( match);
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2015-09-25
        • 1970-01-01
        • 2016-04-16
        • 2021-05-20
        • 2021-08-26
        • 1970-01-01
        • 2021-06-30
        • 2022-01-05
        • 1970-01-01
        相关资源
        最近更新 更多