【发布时间】:2012-08-21 17:02:55
【问题描述】:
我正在尝试将整数列表转换为字符(整数由空格、换行符和制表符分隔)。输入以 EOF 结束。例如, 输入; 72 101 108 108 111 44 32 119 111 114 108 100 33 输出 你好,世界!
#include <stdio.h>
#include <ctype.h>
#define MAXBUFFERSIZE 100
void cleartoendofline( void ); /* ANSI function prototype */
void cleartoendofline( void )
{
char ch;
ch != '\n';
//ch = getchar();
//while( ch != '\n' )
//ch = getchar();
}
main()
{
char ch; /* handles user input */
char buffer[MAXBUFFERSIZE]; /* sufficient to handle one line */
int char_count; /* number of characters read for this line */
int exit_flag = 0;
int valid_choice;
while( exit_flag == 0 ) {
printf("Enter integer(s)\n: ");
//ch = getchar();
scanf("%d",&ch)
char_count = 0;
while( (ch != '\n') && (char_count < MAXBUFFERSIZE)) {
buffer[char_count++] = ch;
ch = getchar();
}
buffer[char_count] = 0x00; /* null terminate buffer */
printf("\nIntegers translates to:\n");
printf("%s\n", buffer);
valid_choice = 0;
while( valid_choice == 0 ) {
printf("Continue (Y/N)?\n");
scanf(" %c", &ch );
ch = toupper( ch );
if((ch == 'Y') || (ch == 'N') )
valid_choice = 1;
else
printf("\007Error: Invalid choice\n");
cleartoendofline();
}
if( ch == 'N' ) exit_flag = 1;
}
}
【问题讨论】:
-
好的,谢谢 Eric,我不知道作业标签
-
“太好了”。那么,什么“不起作用”?如何?是SEGV吗?它不会停止要求输入吗?它会吐出错误的值吗?只是还没有执行“任务”吗?即:问题是什么?
-
它只返回与输出相同的字符串。我尝试使用 %d 无济于事
-
您将一串字符读入缓冲区,然后
printf("%s\n", buffer);。除了打印与您读入的字符串相同的字符串之外,您还期望发生什么? -
您使用
scanf期望一个整数,但读入一个字符。此外,当您将 97 转换为 'a' 或其他内容时,不要假设字符是连续的,就像它们在 ASCII 中一样,或者甚至使用了 ASCII。查看 EBCDIC 以获取相关示例。
标签: c