【问题标题】:Printing out binary ASCII code for a character string in C打印出 C 中字符串的二进制 ASCII 码
【发布时间】:2015-10-16 05:07:32
【问题描述】:

我需要编写一个程序来读取字符串并打印出该字符串的二进制 ASCII 码。我不知道字符串的长度,我需要在程序的某个地方实现数据结构。我写的源代码是:

#include <stdio.h>  
int dec_to_binary(int c, int d);

//initialize data structure for binary value 
struct binary{
    int value;
};
struct word{
    int w_value;
};

int main(){

char wordd[256];
printf("Input a string of characters (no spaces): \n");
//scanf("%s", w);
fgets(wordd, sizeof(wordd), stdin);
printf("You typed: %s", wordd);
int size_word = sizeof(wordd);

struct word w[size_word]; //stores character string
struct binary b[size_word]; //initizalize corresponding binary array for char string inputted by user

int i = 0;
int char_int = 0;
for (i = 0; i < size_word; i++)
{
    char_int = w[i].w_value;
    b[i].value  = dec_to_binary(char_int, size_word); //stores binary value in binary struct array  
}

printf("The binary ASCII code for this string is: %d", b);

return 0;
}

int dec_to_binary(int c, int d)
{
   int i = 0;
   for(i = d; i >= 0; i--){
       if((c & (1 << i)) != 0){
       return 1;
       }else{
       return 0;
     } 
   }
}

当我编译它时,我没有收到任何错误,但我的输出不正确:

Input a string of characters (no spaces):
eli
You typed: eli
The binary ASCII code for this string is: 2421936

无论我尝试什么输入,我都会得到返回值 2421936。关于我哪里出错的任何想法?

【问题讨论】:

    标签: c string binary structure ascii


    【解决方案1】:

    您将b 声明为结构数组,因此如果您打印b 的值,它将为您提供数组的基地址。
    使用循环打印数组值。
    您正在使用 w 获取二进制值,但输入在 wordd[] 中,您是否复制了该值?

    【讨论】:

      【解决方案2】:

      您需要打印数组中各个条目的值而不是 b 的值(它只会打印 b 的地址,因为 b 独立代表指针)

      【讨论】:

        【解决方案3】:

        你还没有初始化w。 请记住 fgets() 将换行符存储在字符串中,因此最好在继续之前将其删除。执行以下操作:

        int i;
        for (i=0; i<size_word; i++) {
            if (wordd[i] == '\0') {
               wordd[i] = 0;
               break;
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-20
          • 1970-01-01
          • 2014-06-14
          • 2021-11-29
          • 2016-06-18
          • 1970-01-01
          • 1970-01-01
          • 2019-04-20
          相关资源
          最近更新 更多