我正在尝试获取像 12340
这样的输入字符串并输出 4321
。奇怪的是,如果我输入一个小于 4 的序列(例如:1230
),输出是正确的(321
)。但如果我输入 12340
,我最终会得到 4321(↨@
。是什么导致了这种行为?
(这不是作业,我正在按照http://www.ltam.lu/cours-c/prg-c58.htm的练习6.8来学习C)
这是我的整个代码(我会发布一个小/简洁的代码示例,但我似乎无法指出问题)
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char array[100];
printf("Shoot me consecutive numbers, end with 0\n");
scanf("%s",&array);
int count = strlen(array);
char countdown[count];
int reverseIndex;
int index = 0;
for(reverseIndex = count-1;reverseIndex >= 0;reverseIndex--)
{
char possibleNumber = array[reverseIndex];
if(isdigit(possibleNumber) && possibleNumber != '0')
{
countdown[index] = possibleNumber;
index++;
}
}
printf("countdown : %s\n",countdown);
return 0;
}
最佳答案
一个直接错误是这一行:
您需要在此行中为 NULL 终止符提供足够的空间:
char countdown[count + 1];//added +1
另一个是:
scanf("%s",&array);
将其更改为:
scanf("%s",array); //%s expects char *, &array is of type char (*)[100], parameter type mismatch
我对原始代码进行了这些编辑(请参阅内联注释),还使用了对 memset()
的调用初始化倒计时,并运行:(结果如下所示)
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main()
{
char array[100];
printf("Shoot me consecutive numbers, end with 0\n");
scanf("%s",array);//removed &
int count = strlen(array);
char countdown[count+1];//add room for NULL terminator
int reverseIndex;
int index = 0;
memset(countdown, 0, count+1);//added to initialize all elements of char array to NULL
for(reverseIndex = count-1;reverseIndex >= 0;reverseIndex--)
{
char possibleNumber = array[reverseIndex];
if(isdigit(possibleNumber) && possibleNumber != '0')
{
countdown[index] = possibleNumber;
index++;
}
}
printf("countdown : %s\n",countdown);
getchar();
getchar();
return 0;
}
输入和输出:
编辑回答有关结果中不需要的字符的评论问题
(和原始问题:...但是如果我输入 12340,我最终会得到 4321(↨@... )
何时 char countdown[count+1];
创建后,不保证其内容。
也就是说,每个位置都可以填充任意随机的位集。
假设数组定义为 char array[5];如果没有初始化,在内存中可能是这样的:
|€|Œ|™|¢|§|
稍后在代码中,您将循环遍历以将每个位置分配给
使用来自标准输入的 scanf() 获取的字符进行填充,这很好,
现在,循环 4 次后看起来像这样:
|1|2|3|4|§|
注意,最后一个位置没有终止 NULL (0)。
通过使用memset(array, 0, 5);
创建的缓冲区将如下所示:
|0|0|0|0|0|
生成的填充缓冲区如下所示:
|1|2|3|4|0| //properly terminated char buf is required for a C string
关于c - 超过 4 个字符输入的倒计时算法中的奇怪字符输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24793315/