[英]printf() isn't being executed
我想编写一个程序,计算一个字符串中每个字母的出现次数,然后打印每个字母之一,然后打印该字母的计数。
例如:
aabbcccd
具有2 a
,2 b
,3 c
和1 d
所以我想将其转换并打印为:
a2b2c3d1
我编写了代码(请参阅下文)以执行此计数/转换,但是由于某些原因,我没有看到任何输出。
#include<stdio.h>
main()
{
char array[]="aabbcccd";
char type,*count,*cp=array;
while(cp!='\0'){
type=*cp;
cp++;
count=cp;
int c;
for(c=1;*cp==type;c++,cp++);
*count='0'+c;
}
count++;
*count='\0';
printf("%s",array);
}
谁能帮助我了解为什么我看不到printf()
任何输出?
char array[]="aabbcccd";
char type,*count,*cp=array;
while(cp!='\0'){
*cp
是一个指向数组起始地址的指针,它永远不会==
指向字符'\\0'
因此它不能离开循环。
您需要引用指针以获取指向的内容:
while(*cp != '\0') {
...
另外,您还有一个;
在for循环之后,跳过其内容:
for(c=1;*cp==type;c++,cp++); <-- this ; makes it not execute the code beneath it
解决这两个问题后,代码将产生输出:
mike@linux-4puc:~> ./a.out
a1b1c2cd
还不是您想要的那个,但是可以解决“ printf无法运行”的问题
顺便说一句,此代码还有其他一些主要问题:
'1'
,其中尾随'\\0'
是,和'\\0'
一个超越这个角色。 '0' + 10
为':'
),则您的代码将不起作用。 "dddd"
不会变成"d4"
;它变成"d4dd"
),那么您的代码将无法正常工作。 可能是行缓冲。 将\\n
添加到您的printf()
格式字符串中。 同样,您的代码也很吓人,如果连续出现9个以上相同字符,会发生什么情况?
1)纠错
while(*cp!='\0'){
并不是
while(cp!='\0'){
2)建议
不要使用array []在结果用户中放置另一个数组,在您的rusel中放置它更合适,也可以
我试图快速解决您的问题,这是我的代码:
#include <stdio.h>
#define SIZE 255
int main()
{
char input[SIZE] = "aabbcccd";/*input string*/
char output[SIZE]={'\0'};/*where output string is stored*/
char seen[SIZE]={'\0'};/*store all chars already counted*/
char *ip = input;/*input pointer=ip*/
char *op = output;/*output pointer = op*/
char *sp = seen;/*seen pointer=sp*/
char c,count;
int i,j,done;
i=0;
while(i<SIZE && input[i]!='\0')
{
c=input[i];
//don't count if already searched:
done=0;
j=0;
while(j<SIZE)
{
if(c==seen[j])
{
done=1;
break;
}
j++;
}
if(done==0)
{//if i never searched char 'c':
*sp=c;
sp++;
*sp='\0';
//count how many "c" there are into input array:
count = '0';
j=0;
while(j<SIZE)
{
if(ip[j]==c)
{
count++;
}
j++;
}
*op=c;
op++;
*op=count;
op++;
}
i++;
}
*op='\0';
printf("input: %s\n",input);
printf("output: %s\n",output);
return 0;
}
由于以下几个原因,它不是一个好的代码(我不检查数组大小来写新元素,我可以在第一个空项目处停止搜索,依此类推...),但是您可以将其视为“起点”并加以改进它。 您可以看看标准库来复制子字符串元素,等等(例如strncpy)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.