gpt4 book ai didi

C 程序帮助输入大写第一个字母

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:13 24 4
gpt4 key购买 nike

我是一名初学者,正在编写一段代码

asks for the user's name

check if the length is >15, if it is, it will ask the user to input a shorter name when they restart the program

if the length is valid, upper case the first letter of the entered name

display something like "Hi name"

但是,无论我输入什么,程序都会一直退出。这是我所做的:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>

int main(void)
{
char str_name[15];

printf("Please enter your first name to begin: ");
scanf_s("%14s", str_name, _countof(str_name));
getchar();

if (strlen(str_name) > 15)
{
printf("The entered name is too long, please restart the program and try again.");
getchar();
exit(0);
}
else
{
str_name[0] = toupper(str_name[0]);

printf("Hi %s.\n", str_name);
getchar();
}

return 0;
}

最佳答案

您可以简单地使用 fgets()读取输入缓冲区。

char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it in a buffer pointed to by str. It stops when either n-1 characters are read, the newline character is read, or the EOF is reached.

关于fgets()的一些注意事项:

  • 出错时返回 NULL
  • 在缓冲区末尾附加 \n 字符。可以用 \0 代替。
  • 缓冲区必须是指向字符数组的指针。分配在堆栈或堆上。
  • stdinFILE 对象中读取。

下面是一些示例代码,说明了这一点:

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

#define NAMESTRLEN 16

int main(void) {
char str_name[NAMESTRLEN] = {'\0'};
size_t slen;

printf("Please enter your first name to begin: ");
if (fgets(str_name, NAMESTRLEN, stdin) == NULL) {
fprintf( stderr, "Error from fgets()\n");
return 1;
}

slen = strlen(str_name);
if (slen > 0 && str_name[slen-1] == '\n') {
str_name[slen-1] = '\0';
} else {
fprintf( stderr, "Too many characters\n");
return 1;
}

if (str_name[0] == '\0') {
fprintf( stderr, "No name entered\n");
return 1;
}

str_name[0] = toupper((unsigned char)str_name[0]);

printf("Hi %s.\n", str_name);

return 0;
}

关于C 程序帮助输入大写第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42106582/

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