代码之家  ›  专栏  ›  技术社区  ›  shea

字符串仅记录第一个单词

  •  3
  • shea  · 技术社区  · 12 年前

    我刚开始用C语言编程,正在编写一个密码/解密程序。用户被要求输入一个短语,该短语被存储为字符*。问题是程序只存储字符串的第一个单词,然后忽略它之后的所有内容

    int maincalc(int k)                         //The Calculation Function for Cyphering
    {
        char *s;
        s=(char*) malloc(sizeof(100));
        printf("Please enter the phrase that you would like to code: ");  
        fscanf(stdin,"%s %99[^\n]", s);
        int i=0;
        int n=strlen(s);
    
        while(i<n)
        {
            if(s[i]>=65&&s[i]<=90)              //For Uppercase letters
            {
                int u=s[i];
                int c=uppercalc(u,k);
                printf("%c",c);
            }
            else if(s[i]>=97&&s[i]<=122)    //For Lowercase letters
            {
                int u=s[i];
                int c=lowercalc(u,k);
                printf("%c",c);
            }
            else 
                printf("%c",s[i]);          //For non letters
            i++;
        }
        free(s);
        printf("\n");
        return 0;
    } 
    

    只需要知道该怎么做才能让程序确认整个字符串的存在,而不仅仅是第一个单词。谢谢

    1 回复  |  直到 12 年前
        1
  •  2
  •   Daniel Fischer    12 年前

    不,两者都不起作用。使用fscanf不需要等待用户输入。它只是简单地打印“请输入短语…”,然后退出fgets也会做同样的事情,程序不等待输入,只打印“PLeasy-enter…”然后退出。

    在该评论中,在编辑之前,您提到了以前的一些输入。我的心理调试能力告诉我,输入缓冲区中仍有来自前一个输入的换行符。那会使

    fgets(s, 100, stdin);
    

    fscanf(stdin, "%99[^\n]", s);
    

    立即返回,因为它们会立即遇到表示输入结束的换行符。

    在获得更多的字符串输入之前,您需要使用缓冲区中的换行符。你可以使用

    fscanf(stdin, " %99[^\n]", s);
    

    格式开头的空间会消耗输入缓冲区中的任何初始空白,或者清除输入缓冲区

    int ch;
    while((ch = getchar()) != EOF && ch != '\n);
    if (ch == EOF) {
        // input stream broken?
        exit(EXIT_FAILURE);
    }
    

    在获得输入之前 fgets fscanf .