如何在同一个变量中停止while循环

时间:2015-09-21 19:22:57

标签: c

我必须输入随机名称和权重,并在我按Enter而不是名称时完成循环。然而,我用来检测输入的方式不能取名,所以得到两个变量。问题是如何使用相同的变量输入测试和名称

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


int main() {

    int c, weight[1000], i = 0;
    char name[1000];
    puts ("Enter the person's name or only enter to end the program");
    if ((c = getchar() == '\n')) {




    } else {

        while (c != '\n') {
            printf("Enter the name");
            scanf("%s", &nome[i]);
            i++;
            printf("Enter the \n");
            scanf("%i", &weight[i]);

        }
    }

    return 0;
}

2 个答案:

答案 0 :(得分:2)

这是一个简单的例子

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

int main(void)
{
    char name[1000] = {0};                      // initialise
    puts ("Enter the person's name or only enter to end the program");
    if (fgets(name, sizeof(name), stdin) != NULL) {
        name [ strcspn(name, "\r\n") ] = 0;     // remove trailing newline etc
        if (strlen(name)) {
            printf("The name entered was: %s\n", name);
        } 
        else {
            printf("You did not enter a name\n");
        }
    }
    return 0;
}

答案 1 :(得分:1)

首先,names是一个字符数组,您将其视为一个字符串数组。其次,需要基于输入退出的循环最清楚地用break表示:

char *names[1000];
int count = 0;

while (1) {
    char *r, buf[1000];
    int len;

    char *r = fgets(buf, 1000, stdin);
    if (NULL == r) break;                 // EOF
    if ((len = strlen(buf)) < 2) break;  // NL only

    r = malloc(len + 1);
    if (NULL == r) break;
    strcpy(r, buf);
    names[count] = r;
    count += 1;

    ...
}

...