C Primer Plus上的一道关于读取字符串的题,有些地方弄不出来,求助。

piginthetree 2008-10-29 10:53:28
题目如下:
编写一个程序。该程序读取输入直到遇到#字符。使程序打印每个输入的字符以及它的十进制ASCII码。每行打印8个字符/编码对。建议:利用字符计数和模运算符%在每8个循环周期时打印一个换行符。

困惑的地方在:读取和打印分别用getchar和putchar的话,每次不是只能存放一个字符么,怎么通过字符计数来统计输入字符的数字?还是要用字符数组来装?
...全文
133 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
piginthetree 2008-10-29
  • 打赏
  • 举报
回复
不知道是不是我钻牛角尖了 呵呵
piginthetree 2008-10-29
  • 打赏
  • 举报
回复
to anybbs:
非常感谢,我发现一个问题,如果输入回车键,窗口立马就显示结果了,而且不满足8个一行的条件,如何解决?
anybbs 2008-10-29
  • 打赏
  • 举报
回复
上面那个有点小错误,改正一下:



int main(void){
int str;
int count = 0;
while((str = getchar()) != '#'){
count++;
printf("%c %#x ", str, str);
if((count%8) == 0) printf("\n");
}
return 0;
}




anybbs 2008-10-29
  • 打赏
  • 举报
回复
随便写了个:

int main(void){
int str;
int count = 0;
while((str = getchar()) != '#'){
count++;
printf("%c %0xx ", str, str);
if((count%8) == 0) printf("\n");
}
return 0;
}


piginthetree 2008-10-29
  • 打赏
  • 举报
回复
有空的大哥最好帮我写一下代码,原书带的答案不是每题都有,郁闷啊。
piginthetree 2008-10-29
  • 打赏
  • 举报
回复
谢谢2位了,特别是anybbs。
anybbs 2008-10-29
  • 打赏
  • 举报
回复
给你一个完整测试版的:


#include <stdio.h>
int main(void){
int str;
char buf[256] = {'\0'};
int count = 0;
int i = 0;
printf("please input less than 256 characters, ended with \'#\' :\n \n");
while((str = getchar()) != '#'){
if(str>=33 && str<=126){
buf[count] = str;
count++;
if(count == 256){ //ºÇºÇ£¬Ã»ÓнáÊø·ûÁË£¬²»¹ýÎÒÃDz»ÓÃs£¬Ò²ÎÞËùνÁË
printf("\n ERROR: bufer is full, please don't input more than 256 characters \n");
break;
}
}
}
printf("The result is :\n");
for(i = 0; i<count; ){
printf("%c %-6d", buf[i], buf[i]);
i++;
if((i%8 == 0) && (i != 0)) printf("\n");
}
return 0;
}
anybbs 2008-10-29
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 piginthetree 的回复:]
to anybbs:
非常感谢,我发现一个问题,如果输入回车键,窗口立马就显示结果了,而且不满足8个一行的条件,如何解决?
[/Quote]




#include <stdio.h>
int main(void){
int str;
char buf[256] = {'\0'};
int count = 0;
int i = 0;
while((str = getchar()) != '#'){
if(str>=33 && str<=126){
buf[count] = str;
count++;
if(count == 256){ //呵呵,没有结束符了,不过我们不用s,也无所谓了
printf("bufer is full");
break;
}
}
}
for(i = 0; i<count; i++){
printf("%c %d ", buf[i], buf[i]);
if(i%8 == 0) printf("\n");
}
return 0;
}

mo4772 2008-10-29
  • 打赏
  • 举报
回复
#include<stdio.h>
#include<conio.h>


int main(void)
{
int str;
int count = 0;
while((str = getchar())!= '#'&&str!='\n')
{
if(str!=' ')
{
count++;
printf("%c %#x ", str, str);
if((count%8) == 0) printf("\n");
}
}
getch();

}


69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧