我已经弄清楚如何获取用户的输入(字符串)并从中获取每个字母并给出每个字母的二进制等值。
问题是我希望每个字母在屏幕上显示时通过每行一个字母来给出二进制数字。我想帮忙。
例如:
C 0 1 0 0 0 0 1 1
h 0 1 1 0 1 0 0 0
a 0 1 1 0 0 0 0 1
n 0 1 1 0 1 1 1 0
g 0 1 1 0 0 1 1 1
这是我使用的代码:
#include <stdio.h>
int main()
{
//get input
printf( "Enter a string: " );
char s[255];
scanf( "%[^\n]s" , s );
//print output
printf( "'%s' converted to binary is: " , s );
//for each character, print it's binary aoutput
int i,c,power;
for( i=0 ; s[i]!='\0' ; i++ )
{
//c holds the character being converted
c = s[i];
//for each binary value below 256 (because ascii values < 256)
for( power=7 ; power+1 ; power-- )
//if c is greater than or equal to it, it is a 1
if( c >= (1<<power) )
{
c -= (1<<power); //subtract that binary value
printf("1");
}
//otherwise, it is a zero
else
printf("0");
}
return 0;
}
答案 0 :(得分:1)
处理每个字符后,您只需添加printf("\n")
语句。
for( i=0 ; s[i]!='\0' ; i++ )
{
//c holds the character being converted
c = s[i];
//for each binary value below 256 (because ascii values < 256)
for( power=7 ; power+1 ; power-- )
//if c is greater than or equal to it, it is a 1
if( c >= (1<<power) )
{
c -= (1<<power); //subtract that binary value
printf("1");
}
//otherwise, it is a zero
else
printf("0");
/* Add the following statement, for this to work as you expected */
printf("\n");
}
答案 1 :(得分:0)
不要立即打印1
和0
,而是从中构建字符串。然后打印出你刚刚建立的字符串旁边转换的字符。
答案 2 :(得分:0)
要在新行上打印每个字符,请在打印每个字符后打印换行符:
printf("\n");
要先打印角色,请使用putchar:
putchar(c);
答案 3 :(得分:0)
抛开糟糕的代码风格,看起来你想要的只是一个简单的
printf("\n");
紧跟在外部for循环末尾的printf("0");
之后的语句,以添加换行符。