0

我对 C 非常陌生,并且涉足 Objective-C、AppleScript 和 HTML/CSS。我确信我的问题很容易解决。我正在尝试编写一些允许我输入源数据并以某种方式将其排序为输出(在本例中为引用)的东西。基本上,我想将名称、标题、出版商等保存为变量并按一定顺序打印它们。

这就是问题所在:这里的代码过早终止,当我将 fputs 和 fgets 与 stdout 和 stdin 一起使用时,它会卡住并永远问同样的问题。我错过了什么?

int source_type;
int NumberofAuthors;
char AuthorName1[20];
char AuthorName2[20];
char AuthorName3[20];
char title[20];
char url[100];
char publishingCity[20];
char publisher[20];
char yearPublished[20];
char pageNumbers[20];
int valid;

printf("Welcome to Jackson's Chicago Manual of Style Auto-Footnoter.\n");

fputs("Choose source type:\n a.Book\n b.Journal\n c.Article\n d.Website\n ", stdout);
source_type = getchar();

if (source_type == 'a') {
    valid = 1;
} else {
    printf("Invalid source selection");
}

while ( valid == 1 && source_type == 'a' )
{
    printf("Number of authors [1 or 2]: ");
    scanf( "%d", &NumberofAuthors);
    if ( NumberofAuthors > 0 && NumberofAuthors < 3 ) {
        valid = 1;
        printf("Got it, %d author(s).\n", NumberofAuthors);
    }
    else {
        printf( "That's not enough people to write a book.\n" );
    }

    if ( NumberofAuthors == 1 ) {
        printf( "Author's name: " );
        scanf("%c", &AuthorName1);

    } 
    if (NumberofAuthors == 2) {
        printf("First author's name: " );
        scanf("%c", &AuthorName2);
        printf("Second author's name: " );
        scanf("%c", &AuthorName3);
    }
    else {
        valid = 0;
    }

    printf("Book title: " );
    fgets(title, sizeof(title), stdin);

    printf("Publication city: " );
    fgets(publishingCity, sizeof(publishingCity), stdin);


    } 


return 0;
4

3 回答 3

1

在节目开始时:

if (source_type == 'a') {
    valid = 1;
} else {
    printf("Invalid source selection");
}

如果source_type是无效的,valid仍然包含垃圾值,并且使用未初始化的变量是未定义的行为。继续。

while ( valid == 1 && source_type == 'a' )
{
    printf("Number of authors [1 or 2]: ");
    scanf( "%d", &NumberofAuthors);
    if ( NumberofAuthors > 0 && NumberofAuthors < 3 ) {
        valid = 1;
        printf("Got it, %d author(s).\n", NumberofAuthors);
    }
    //...

您永远不会重置valid0. 您应该考虑使用switch()for 循环的那部分。它使它更易于阅读。

if ( NumberofAuthors == 1 ) {
    printf( "Author's name: " );
    scanf("%c", &AuthorName1);

} 
if (NumberofAuthors == 2) {
    printf("First author's name: " );
    scanf("%c", &AuthorName2);
    printf("Second author's name: " );
    scanf("%c", &AuthorName3);
}
else {
    valid = 0;
}

我希望你意识到,如果NumberofAuthors == 1else部分将被执行和设置valid = 0。那是因为 else 只停留在最接近的 if 上,并且只有那个。

我猜你使用 fgets 等来避免溢出。好的。看到s上的那个把戏scanf。在这里阅读更多:http ://www.cplusplus.com/reference/clibrary/cstdio/scanf/

试试看:

int main(int argc, char* argv[])
{
    char source_type;
    int NumberofAuthors;
    char AuthorName1[20];
    char AuthorName2[20];
    char AuthorName3[20];
    char title[20];
    char url[100];
    char publishingCity[20];
    char publisher[20];
    char yearPublished[20];
    char pageNumbers[20];
    int valid;

    printf("Welcome to Jackson's Chicago Manual of Style Auto-Footnoter.\n");

    printf("Choose source type:\n a.Book");
    scanf("%c" , &source_type);

    if (source_type == 'a') {
        valid = 1;
    } else {
        printf("Invalid source selection");
        valid = 0;
    }

    while ( valid == 1 && source_type == 'a' )
    {
        //Reset
        valid = 0;

        printf("Number of authors [1 or 2]: ");
        scanf( "%d", &NumberofAuthors);
        if ( NumberofAuthors > 0 && NumberofAuthors < 3 ) {
            valid = 1;
            printf("Got it, %d author(s).\n", NumberofAuthors);
        }
        else {
            printf( "That's not enough people to write a book.\n" );
            continue;
        }

        switch( NumberofAuthors )
        {
        case 1:
            printf( "Author's name: " );
            scanf("%19s", AuthorName1);
            break;

        case 2:
            printf("First author's name: " );
            scanf("%19s", AuthorName2);
            printf("Second author's name: " );
            scanf("%19s", AuthorName3);
            break;

        default:
            valid = 0;
            break;
        }

        if(valid)
        {
            printf("Book title: " );
            scanf("%19s" , title);

            printf("Publication city: " );
            scanf("%19s" , publishingCity );
        }

    } 
    return 0;
}
于 2011-11-05T00:30:56.050 回答
0

%c用来读名字;情况不妙。您传递的是数组的地址,而不是指向数组第一个元素的指针;这也不好。你到处践踏,给自己留下不确定的行为问题。

'明显' 的解决方法是使用%s和放弃&数组名称前面的,但你不能屈服于明显的,因为它是错误的。大多数作者的名字和姓氏(或首字母和姓氏)之间有一个空格,并%s在第一个空格处停止。您需要使用fgets()来读取名称,但请记住删除尾随的换行符。

我不太清楚为什么“AuthorName1”中有一个作者的名字,但“AuthorName2”和“AuthorName3”中有两个作者;无论如何,我希望对第一作者使用“名称 1”。事实上,拥有一组作者姓名可能会更好——这样更容易概括。

当我编译您的代码时(将其包装在int main(void) {and中}并包含<stdio.h>,我会收到编译警告:

xx.c: In function ‘main’:
xx.c:43: warning: format ‘%c’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’
xx.c:43: warning: format ‘%c’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’
xx.c:48: warning: format ‘%c’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’
xx.c:48: warning: format ‘%c’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’
xx.c:50: warning: format ‘%c’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’
xx.c:50: warning: format ‘%c’ expects type ‘char *’, but argument 2 has type ‘char (*)[20]’

我重写了代码以使用函数来处理字符串的提示和读取,因此:

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

static int get_string(const char *prompt, char *buffer, size_t bufsiz)
{
    char *nl;
    printf("%s: ", prompt);
    fflush(0);
    if (fgets(buffer, bufsiz, stdin) == 0)
        return EOF; /* Read error - EOF */
    if ((nl = strchr(buffer, '\n')) == 0)
    {
        fprintf(stderr, "Overlong string entered!\n");
        return EOF;
    }
    *nl = '\0';
    return 0;
}

int main(void)
{
    int source_type;
    int NumberofAuthors;
    char AuthorName1[20];
    char AuthorName2[20];
    char title[20];
    char publishingCity[20];
    int valid = 0;
    int c;

    printf("Welcome to Jackson's Chicago Manual of Style Auto-Footnoter.\n");

    fputs("Choose source type:\n a.Book\n b.Journal\n c.Article\n d.Website\n ", stdout);
    source_type = getchar();

    if (source_type == 'a')
        valid = 1;
    else
    {
        printf("Invalid source selection");
        return(1);
    }

    /* Lucky that scanf() skips over the newline in search of digits! */
    while (valid == 1 && source_type == 'a')
    {
        printf("Number of authors [1 or 2]");
        scanf("%d", &NumberofAuthors);
        if (NumberofAuthors > 0 && NumberofAuthors < 3)
        {
            valid = 1;
            printf("Got it, %d author(s).\n", NumberofAuthors);
        }
        else
        {
            printf("That's not enough (or too many) people to write a book.\n");
            break;
        }
        /* Gobble to newline */
        while ((c = getchar()) != EOF && c != '\n')
            ;

        if (NumberofAuthors == 1)
        {
            if (get_string("Author's name", AuthorName1, sizeof(AuthorName1)) == EOF)
            {
                valid = 0;
                break;
            }
        } 
        else
        {
            assert(NumberofAuthors == 2);
            if (get_string("First author's name",  AuthorName1, sizeof(AuthorName1)) == EOF ||
                get_string("Second author's name", AuthorName2, sizeof(AuthorName2)) == EOF)
            {
                valid = 0;
                break;
            }
        }

        if (get_string("Book title", title, sizeof(title)) == EOF ||
            get_string("Publication city", publishingCity, sizeof(publishingCity)) == EOF)
        {
            valid = 0;
            break;
        }

        printf("Author 1: %s\n", AuthorName1);
        if (NumberofAuthors == 2)
            printf("Author 2: %s\n", AuthorName2);
        printf("Book title: %s\n", title);
        printf("Publication city: %s\n", publishingCity);
    } 

    return 0;
}

我保留了“有效”标志,但它确实不值得。没有它,代码会更简单更短。

于 2011-11-05T01:16:17.293 回答
0

您只能source_type在循环之外进行更改while,因此一旦进入循环,唯一退出的方法就是分配0valid. 每次都这样做NumberofAuthors != 2,因为第一个if不在if-else链内。也许你想要这个:

if ( NumberofAuthors == 1 ) {
    printf( "Author's name: " );
    scanf("%c", &AuthorName1);
} else if (NumberofAuthors == 2) {
    printf("First author's name: " );
    scanf("%c", &AuthorName2);
    printf("Second author's name: " );
    scanf("%c", &AuthorName3);
} else {
    valid = 0;
}
于 2011-11-04T23:48:21.793 回答