我只是一个初学者,所以请不要过于武断。 我想了解,当 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/