gpt4 book ai didi

c - 使用 Break 终止 for 循环

转载 作者:行者123 更新时间:2023-12-02 08:15:56 27 4
gpt4 key购买 nike

所以,一个非常基本的程序,我希望允许用户在文本文件中输入最多 10 个单词。

我想做一个退出子句,这样如果用户输入一个特定的词,程序就会停止

我正在尝试使用 strcmp 并将“exit”与用户输入的词进行比较。如果两者匹配,则终止。我知道如果两者相同则返回 0,但是我无法写:

{
char word[10];
FILE *fp;
int x;
int words = 0;

fp = fopen("c:\\CTEMP\\ExamProg1.txt", "w+");

{

for (x = 0; x < 10; x++)

{
printf("\nType the word you want to add. Type exit to terminate: ");
scanf("%s", word);

if (strcmp(word, "exit") == 0)
{
break;
}

fprintf(fp, "%s\n", word);
words++;
}

fclose(fp);
}

scanf_s("%d");

}

我怎样才能在输入 exit 时继续中断程序,而不是必须插入两次“exit”?

最佳答案

您的代码有很多问题:

  1. scanf("%s", &word); 因为字符串本身就是一个指针或数组,所以在调用 scanf 将扫描的输入读入字符串。只需使用:scanf("%s", word);

  2. strcmp(word, "exit")=0= 运算符是赋值运算符,而不是比较运算符(您想要的是 strcmp(word, "exit") == 0)。您对单词“exit”的测试失败了,因为您没有正确检查 strcmp 的返回值。

关于c - 使用 Break 终止 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41834203/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com