【问题标题】:String and for loop [duplicate]字符串和for循环[重复]
【发布时间】:2018-10-02 04:20:14
【问题描述】:

我编写了这个 C 程序来输入 3 个人的姓名和年龄。但输出不是我的预期。它可以输入第一人称的姓名和年龄,但不能输入第二人称和第三人称。请帮忙。

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

int main()
{
    int i, age;
    char name[20];

    for(i=0; i<3; i++)
    {
        printf("\nEnter name: ");
        gets(name);

        printf("Enter age: ");
        scanf(" %d", &age);

        puts(name);
        printf(" %d", age);
    }

    return 0;
}

【问题讨论】:

  • 你应该检查scanf()的返回值。在您的第二个循环中,如果您输入了一个名称,则该名称可能不会被 %d 转换,并且会留在输入中以便在下一次循环中读取 - 同时让您对正在发生的事情感到困惑。请参阅 Why the gets() function is to dangerous to be used — ever! 了解为什么不应该使用 gets() 以及有哪些替代方案可用。您应该测试替换(可能是fgets())是否成功。始终检查输入操作!
  • 感谢您的建议。

标签: c string


【解决方案1】:

简而言之:您的第二个puts 正在处理来自您的scanf'\n'

通过在scanf 之后添加getchar(); 进行修复

解释:

第一次迭代:

    printf("\nEnter name: ");
    gets(name);                     // line is read from input
    printf("Enter age: ");
    scanf(" %d", &age);             // a number is read from input, and the newline char ('\n') remains in buffer
    puts(name);
    printf(" %d", age);

第二次迭代:

    printf("\nEnter name: ");
    gets(name);                     // previously buffered newline char is read, thus "skipping" user input
    printf("Enter age: ");
    scanf(" %d", &age);             
    puts(name);
    printf(" %d", age);

第三次迭代也是如此,这就是您丢失用户输入的原因

【讨论】:

  • 现在可以使用了。谢谢
【解决方案2】:

存储多人信息的最佳方式是使用struct,比如

  struct person {
      int age;
      char name[20];
  };

并制作结构数组,例如

 struct person people[3];

比使用循环访问people[i].agepeople[i].name,例如:

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

struct person {
    int age;
    char name[20];
};

#define ARR_SIZE 3

int main(int argc, char* argv[])
{
    struct person people[ARR_SIZE];
    int i;
    char *lastpos;
    for(i = 0; i < ARR_SIZE; i++)
    {
        printf("\nEnter name: ");
        scanf(" %s", people[i].name);
        if ((lastpos=strchr(people[i].name, '\n')) != NULL) *lastpos = '\0'; // remove newline from the end
        printf("Enter age: ");
        scanf(" %d", &people[i].age);
    }
    printf("This is the people you entered:\n");    
    for(i = 0; i < ARR_SIZE; i++)
    {
        printf("%d : %s : %d\n", i+1, people[i].name, people[i].age);
    }
    return 0;
}

更新:

如您所见,我使用scanf(" %s", people[i].name); 而不是gets(people[i].name);stdin 读取name。在以下情况下尝试这两种选择:

  • 输入简称(例如 John)和正确的年龄(例如 15 岁)
  • 输入两个单词的名字(例如 John Smith)和正确的年龄(例如 17)
  • 输入短名称和不正确的年龄(例如五岁)

然后阅读有关scanfcleaning input buffer返回值的文章

【讨论】:

  • 谢谢。我是 C 语言的初学者。但我会保留这个以供以后学习 Struct 使用。
  • 祝你学习 C 好运...保持一只脚在另一只脚前面
猜你喜欢
  • 2021-10-06
  • 1970-01-01
  • 2017-01-30
  • 2023-03-20
  • 2019-10-03
  • 1970-01-01
  • 2017-07-10
  • 2021-07-21
  • 1970-01-01
相关资源
最近更新 更多