gpt4 book ai didi

c - scanf 不等待输入

转载 作者:行者123 更新时间:2023-11-30 16:39:52 25 4
gpt4 key购买 nike

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include "contacts.h"


int main(void)
{
int i = 0;
char middleInitial_ans;

// Declare variables here:
struct Name emp[] = { { 0 } };
struct Address addr[] = { { 0 } };
struct Numbers phone[] = { { 0 } };

// Display the title
puts("Contact Management System");
puts("-------------------------");

// Contact Name Input:

printf("Please enter the contact's first name: ");
scanf("%s", emp[i].firstName);
// PRINTING OUT FIRSTNAME
printf("%s\n\n", emp[i].firstName);

printf("Do you want to enter a middle intial(s)? (y or n): ");
scanf("%s", &middleInitial_ans); // Why doesn't the code work when I have %c instead of %s
printf("%c", middleInitial_ans);

if (middleInitial_ans == 'y') {
printf("Please enter the contact's middle initial(s): ");
scanf("%s", emp[i].middleInitial);
printf("\n%s\n", emp[i].middleInitial);

所以最后我要求用户输入字符“y”或“n”,看看他们是否想输入中间名首字母。但是,当我使用 %c 时,因为它们将输入单个字符,所以程序完全跳过此代码。当我使用 %s 时,程序可以识别代码并且工作正常。我想知道为什么会发生这种情况?

最佳答案

C 中的“&”基本上是按值传递,变量能够存储存储值的内存地址。

为此你需要更大的内存。就像数组或缓冲区一样。%s 期望相应的参数为 char * 类型,对于 scanf

char middleInitial_ans2[];

将此用于 %s

关于c - scanf 不等待输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46894399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com