printf()没有被执行

时间:2012-10-23 14:07:03

标签: c printf

我想编写一个程序来计算字符串中每个字母的出现次数,然后打印每个字母中的一个,然后打印该字母的计数。

例如:

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()的任何输出?

5 个答案:

答案 0 :(得分:3)

char array[]="aabbcccd";
char type,*count,*cp=array;
while(cp!='\0'){ 

*cp是一个指向数组起始地址的指针,它永远不会是==到char '\0'所以它不能离开循环。< / p>

您需要使用指针来获取它所指向的内容:

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 not functional”来解决你的问题

答案 1 :(得分:3)

顺便提一下,此代码还有一些其他主要问题:

  1. 如果最后一个字符出现一次,你会尝试写过字符串的结尾(你写的是'1',其尾随'\0',而'\0'一个字符超出该字符。
  2. 如果某个字符的显示次数超过9次('0' + 10':'),则您的代码无效。
  3. 如果某个字符出现次数超过2次("dddd"未成为"d4";它变为"d4dd"),则您的代码无效。

答案 2 :(得分:1)

可能是行缓冲。在\n格式字符串中添加printf()。你的代码也非常可怕,如果一行中有超过9个相同的字符会发生什么?

答案 3 :(得分:0)

1)纠错

while(*cp!='\0'){

而不是

while(cp!='\0'){

2)建议

不要使用array []在你的结果中添加另一个数组来放入你的rusel它更合适和eay

答案 4 :(得分:0)

我试图快速解决您的问题,这是我的代码:

#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)。