簡體   English   中英

在while循環中將scanf用於char數組

[英]Using scanf for char array in while loop

我是C編程新手。 我很想知道我學了多少C語言。因此,我想到了創建一個程序的方法,可以在其中簡單地創建文件並寫入其中。 我認為文件名應少於100個字符。 但是,它是一個字符串還是一個單詞或一個字母都沒有關系。 我無法完成,因為我堅持如何為文件名輸入字符串(例如,Project work,New Doc1等)

所以我寫了這個

int main()
{

    int a = 0;

    while(a != 5)
    {
        puts("Put a number: ");
        scanf("%i", &a);
        if(a == 1)
        {
            char name[30];
            printf("Put a name: ->>");
            for(int i = 0;i < 31 && name[i] != '\n';i++)
            {
                name[i] = getchar();

            }
            char ex[50] = ".txt";

            strcat(name,ex);
            printf("%s",name);

        }
    }

    return 0;
}

問題是在輸入名稱時,它不會在下一個(當我按Enter鍵時)停止,並且在某些情況下它也不會打印正確的文件名。

您的方法有很多問題。

  1. 將scanf與其他輸入原語混合使用不是很好,您必須從所有剩余字符中清除標准輸入。
  2. 任何字符串都必須以“ \\ 0”結尾,以將該字符串標記為完整。 因此,您必須為此字符保留空間。
  3. 連接時,您必須遵守字符串的限制。
  4. 如果您使用printf,則僅在刷新標准輸出后才顯示該字符串(當在字符串末尾添加“ \\ n”時,將完成刷新)

嘗試這個:

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

int main()
{

    int a = 0;

    while(a != 5)
    {
        int ch;
        puts("Put a number: ");
        scanf("%d", &a);
        /* flush any remaining characters */
        while ((ch=getchar()) != EOF && ch != '\n'); /* issue 1 */
        if(a == 1)
        {
            int i = 0;
            char name[30];
            printf("Put a name: ->>");
            fflush(stdout); /* issue 4 */

            while ((ch=getchar()) != EOF && ch != '\n' && i < 25) /* issue 3 */
                name[i++] = ch;
            name[i] = '\0'; /* issue 2 */

            /* flush any remaining characters [if input > 25 chars] */
            if (ch != EOF && ch != '\n') while ((ch=getchar()) != EOF && ch != '\n');

            char ex[50] = ".txt";

            strcat(name,ex); /* issue 3 */
            printf("%s\n",name);

        }
    }

    return 0;
}

另外,考慮使用getlineatoi代替getcharscanf

#include<stdio.h>
main()
{
    static char stop_char='y';
    char input=0;
    do{
        printf("please input a character\n");
        scanf("\n%c",&input);
    }while(input!=stop_char);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM