c - while循环,当它运行 "string"数据时,如何用特定的单词或字母中止它?

标签 c arrays string while-loop

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

while(name1!='q'){
}

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

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

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

#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;
}

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

最佳答案

 while (abort!=0)
 {
   ...
   short abort=strcmp(name1,abort_name);
 }

隐藏while语句上方的main例程中定义的abort变量:这些是2 个独立的变量,因此您的状况永远不会改变。

将其更改为:

abort=strcmp(name1,abort_name);

分配主abort变量。

(请注意,check1 也存在同样的问题)

另请注意:

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

定义一个包含 4 个字符串的数组。不是您想要的,而是您需要的:

const char abort_name[]="stop";

const char *abort_name="stop";

(顺便说一句,让编译器计算大小,由于 nul 终止符,4 是不够的)

关于c - while循环,当它运行 "string"数据时,如何用特定的单词或字母中止它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46644755/

相关文章:

c - strtol帮助为什么它返回0

C 指针(使用指针时 int 和 char 之间的区别),示例如下?

c++ - 求解联立模方程的代码?

c++ - 对输入的数字进行排序 - FOR 和 WHILE 之间的区别

javascript - 将 PHP 数组传递到 cookie 并使用 jQuery 检索

c - 如何在 C 中指定范围?

c - 如何将函数输出(数组)分配给c中的另一个函数?

string - 尝试将 byte slice 解析为 Golang 中的 16 进制数

javascript - 无法在 Javascript 中获取 ArrayBuffer 对象的值

c++ - 字符串统计函数