gpt4 book ai didi

c - 我似乎无法理解是什么在这个 C 程序中创建了下一行

转载 作者:行者123 更新时间:2023-12-02 05:49:27 25 4
gpt4 key购买 nike

(作业题)这个程序的目的是将每个字符串的第一个字母大写,但是我需要在输入后面加一个句点。我似乎无法这样做,因为函数 capital 出于某种我不知道的原因生成\n 。任何帮助,将不胜感激!我只需要那一点,其他的我都有。

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int capital(char s[])
{
int i;
for(i=0; i<strlen(s); i++)
{
if (i==0||(s[i-1]==' '&&s[i]>='a'&&s[i]<='z'))
s[i]=toupper(s[i]);
}
printf("%s.", s);

return 0;
}

int main()
{
char s[100];
printf("Please enter a line of text > ");
fgets(s, sizeof(s), stdin);
capital(s);
return 0;
}

所以例如我希望输出看起来像

Please enter a line of text > help me stackoverflow
Help Me Stackoverflow.

与现在相反

Please enter a line of text > help me stackoverflow
Help Me Stackoverflow
.

最佳答案

fgets保留换行符。

7.21.7.2 The fgets function

#include <stdio.h>
char *fgets(char * restrict s, int n, FILE * restrict stream);

2 The fgets function reads at most one less than the number of characters specified by nfrom the stream pointed to by stream into the array pointed to by s. No additionalcharacters are read after a new-line character (which is retained) or after end-of-file. Anull character is written immediately after the last character read into the array.


一些其他的东西:

  1. 在终止条件中使用 strlen 是个坏主意。
    它使您的算法成为二次算法,除非您的编译器成功确定字符串在循环中没有被缩短,并且您真的不想依赖它。

    改为测试 s[i]

  2. 请注意,toupper 仅在某些具有单字节字符集的语言环境中才能正常工作。
    (同样适用于 iswhite,您可能想用它来检查空格。)

    无论如何,既然您在调用它之前已经检查了 'a'-'z',为什么不直接完成它呢?

     if ((!i || s[i-1]== ' ') && s[i]>='a' && s[i]<='z')
    s[i] += 'A' - 'a';

    (顺便说一句:您的情况有点奇怪。)

关于c - 我似乎无法理解是什么在这个 C 程序中创建了下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27326484/

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