【问题标题】:How to exit the program immediately using strcmp() without printing the next line如何使用 strcmp() 立即退出程序而不打印下一行
【发布时间】:2020-07-19 13:55:06
【问题描述】:

代码本身是关于输入一个字符串和一个字符,程序打印出该字符在特定字符串中的位置。

我想添加的是在输入“end”这个词时立即退出程序,使用strcmp()

目前的问题是,虽然我输入了“end”这个词,但我需要输入一个字符才能让程序结束。

我想要的是程序在输入“end”后立即结束。

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

void input(char*, char*);
int strcheck(char*, char);

int main()
{
    int count;
    char str[100], ch;

    while (1) {
        input(str, &ch);
        if (strcmp(str, "end") == 0) {      //I'm guessing this part is the problem
            break;
        }
        else {
            count = strcheck(str, ch);
            if (count == -1) {
                printf("\"%s\" string doesn't have '%c'. \n\n", str, ch);
            }
            else {
                printf("\"%s\" string has '%c' in position number %d .\n\n", str, ch, count + 1);

            }
        }
    }
    return 0;
}

void input(char* strp, char* chp)
{
    printf("# enter string : ");
    scanf("%s", strp);
    printf("# enter character : ");
    scanf(" %c", chp);
    return;
}

int strcheck(char* strp, char chp)
{
    int i;
    int size = strlen(strp);
    for (i = 0; i < size; i++) {
        if (strp[i] == chp) {
            return i;
        }
    }
    return -1;
}

这段代码的结果是……

# enter string : end
# enter character : a

但我想要的是……

# enter string : end    //--> exit immediately

【问题讨论】:

  • 所以您希望您的程序在输入end 后立即存在?或者它应该在输入end + Enter 后退出?如果输入是dividend怎么办?
  • 所以我要做的是输入end + Enter,拜托:)

标签: c exit strcmp


【解决方案1】:

问题是在检查字符串之前总是询问字符,这是因为字符串和字符输入例程在输入函数中,在检查字符串之前完全执行,有多种方法可以解决这个问题。

要求必须在字符之前检查字符串,一种方法是将此检查移至输入函数:

void input(char *strp, char *chp)
{
    printf("# enter string : ");
    scanf(" %99s", strp); // the input size should be limited to the container capacity
                          // %99s -> 99 characters + null terminator at most
    if (strcmp(strp, "end") == 0)
    {
        exit(0);  //exit() requires #include <stdlib.h>
    }

    printf("# enter character : ");
    scanf(" %c", chp);
    return;
}
int main()
{
    int count;
    char str[100], ch;

    while (1)
    {
        input(str, &ch);

        count = strcheck(str, ch);
        if (count == -1)
        {
            printf("\"%s\" string doesn't have '%c'. \n\n", str, ch);
        }
        else
        {
            printf("\"%s\" string has '%c' in position number %d .\n\n", str, ch, count + 1);
        }
    }
    return 0;
}

【讨论】:

  • 作为一个初学者,我不知道有一个“exit(0); //exit() 需要#include ”!非常感谢:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
  • 2019-04-28
  • 2015-02-14
相关资源
最近更新 更多