gpt4 book ai didi

c - C语言中如何输入新行直到遇到空行

转载 作者:行者123 更新时间:2023-11-30 20:33:28 31 4
gpt4 key购买 nike

这是我的代码,我正在尝试创建一个程序,使用函数对字符进行计数,然后在遇到空行时确定字符的平均值。该程序应该允许用户输入多行,直到遇到空行,但我似乎不能。

#include <stdio.h>
#include <Windows.h>

int main()
{
char str[1000];
int Digits, Char, SpecialChar, linecount = 0;
int counter;
int total;
int average;

Digits = Char = SpecialChar = 0;

printf("Please type in your words here: ");
gets(str);

for (counter = 0; str[counter] != NULL; counter++)
{

if (str[counter] >= '0' && str[counter] <= '9')
Digits++;
else if ((str[counter] >= 'A' && str[counter] <= 'Z') || (str[counter] >= 'a' && str[counter] <= 'z'))
Char++;
else
SpecialChar++;
}

while (str[counter] != '\n')
{
if (str[counter] = '\n')
{
linecount ++;
}
}

total = Digits + Char + SpecialChar;
average = total / linecount;

printf("\nDigits: %d \nCharacters: %d \nSpecial Characters: %d \nLine: %d", Digits, Char, SpecialChar, linecount);
printf("\nTotal no. of characters = %d", total);
printf("\nAverage no. of characters = %d", average);

Sleep(5000000);
return 0;
}

最佳答案

据我所知,函数gets在“\n”之后被中断。另外,使用 fgets 时,您必须注意字符串上的“\0”添加。这意味着

The programme is suppose to allow the user to enter multiple lines until an empty line is encountered but I can't seem to.

使用这种方式永远无法完成。因为 gets 不是推荐的函数,所以我以您可能正在搜索的方式稍微编辑了您的代码。

需要提及的是,在您阅读此代码之前我发现这可能是一个逻辑错误

for (counter = 0; str[counter] != NULL; counter++)

这看起来很奇怪,因为 fgets 总是会记录“\n”字符。所以,下一个条件

if (str[counter] = '\n')

永远不会是真的

我在您的代码中看到了一些其他错误,但不是主要错误。因此,我认为该建议足以任命他们

while (fgets(str, 1000, stdin) && str[0] != '\n'){ //I dont know if checking the first element of the string is redundancy, 
//because, the I think the fgets function will return NULL if you just press enter, as the first character

for (counter = 0; str[counter] != '\n'; counter++{

if (str[counter] >= '0' && str[counter] <= '9')
Digits++;
else if ((str[counter] >= 'A' && str[counter] <= 'Z') || (str[counter] >= 'a' && str[counter] <= 'z'))
Char++;
else
SpecialChar++;
}

linecount ++; //new line is someting that you will always reach, so,
//there is no reason for any condition

}

关于c - C语言中如何输入新行直到遇到空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45259984/

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