Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C程序给出了奇怪的结果_C - Fatal编程技术网

C程序给出了奇怪的结果

C程序给出了奇怪的结果,c,C,我刚开始编程,想出了一个程序来计算输入中的字符数 代码如下: #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { int number = 0; int counter = 0; char sentence[20]; printf("Enter a sentence: "); scanf("%s", sentence);

我刚开始编程,想出了一个程序来计算输入中的字符数

代码如下:

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

int main()
{
    int number = 0;
    int counter = 0;
    char sentence[20];

    printf("Enter a sentence: ");
    scanf("%s", sentence);

    while ( sentence[number] != '\n' )
    {
        counter += 1;
        number += 1;
    }

    printf("no. of characters in sentence you just typed: %d", counter);

    return 1;    
}
#包括
#包括
#包括
int main()
{
整数=0;
int计数器=0;
char语句[20];
printf(“输入一个句子:”);
scanf(“%s”,句子);
while(句子[数字]!='\n')
{
计数器+=1;
数字+=1;
}
printf(“您刚才键入的句子中的字符数:%d”,计数器);
返回1;
}
这个程序有一个奇怪的行为,我无法理解。它编译时不会出错,但无论我键入多少个字符或输入了什么字符,它都会将字符数显示为817


我很好奇为什么是817?真奇怪。另外,请告诉我如何改进我的代码,因为它没有按预期执行。

scanf
带有参数
“%s”
读取一个单词,直到第一个空格、制表符或换行符,并且不会在输入中包含任何
\n
字符。你的循环永远不会结束。或者,更准确地说,它将给出C标准所称的“未定义的行为”。实际上,这意味着它将继续循环,直到它在内存中的某个位置找到新行(可能从开始的817个位置!),或者到达分配内存的末尾并崩溃。

scanf读取输入直到
\n
,但不包括它:

while ( sentence[number] != '\n' ) // always true for legal array bound
将导致非法内存访问,导致未定义的行为。如果您确实希望读取包含字符的字符串,请使用

如果要计算字符数,请将
while
循环更改为

while ( sentence[number] != '\0' )
如果您读取该函数,则函数
scanf
不会读取空白

将while循环更改为

while (sentence[number] != 0 && sentence[number] != '\n')

只需更改这一行:

while ( sentence[number] != '\n' )


在结尾处返回0

这是一个更好的用于计算字符数的代码版本

#include <stdio.h>
main(){
    double c;
    for(n=0; getchar() != EOF; ++n);
    printf("%.0f\n", n);
}
#包括
main(){
双c;
for(n=0;getchar()!=EOF;++n);
printf(“%.0f\n”,n);
}

值得一提的是op为什么要更改此选项:-)如果您使用调试器,您会很容易发现问题。无需尝试调试。投票结束。下一步…………字符串存储在哪里?什么是double c?double是一种类似int的数据类型,如果输入字符串的长度很长,我就使用它。字符串不是存储在这里的,它只是计算输入的字符数。您不应该将整数值存储在
double
中。如果太高的话,Double会失去准确性。一个
int
就足够了,它最多可以计算2GB(如果使用无符号,则为4)的值,而用户实际上不会输入这些值。如果您需要更多,您可以使用
long
,它可以存储8个EB,远远超出预期)。然后,您还将递增
n
,这是从未定义过的,您已经丢弃了接收到的所有字符,这个循环将不会结束,直到输入流关闭,而不是用户按enter键。虽然此代码片段可以解决问题,但确实有助于提高您的帖子质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。还请尽量不要用解释性注释挤满你的代码,这会降低代码和解释的可读性!
#include <stdio.h>
main(){
    double c;
    for(n=0; getchar() != EOF; ++n);
    printf("%.0f\n", n);
}