使用for循环分配C字符串

时间:2014-10-23 03:06:21

标签: c++

我认为这是一个相关主题,在浏览这个论坛和教程时,我已经将我的c-string调整为正确的格式(我认为),但只有一个主题缺失。我们如何使用for循环获取整数,并从整数中分配c-string值。

我现在只关注整数到二进制部分,我确信我的数字操作是可靠的。但是,我的教授说我们需要将二进制值分配给c-string。我尝试这个,它告诉我我通过编译器使用const char和char *。我不确定这是怎么回事,或者如何预防。

这是我的源代码:

//sample integer to binary

#include <iomanip>
#include <iostream>
#include <iomanip>
#include <cstring>

using namespace std;

int main()
{
    int num; //the number a user enters
    int rem; //the remainder, the 1 and 0 of the binary number
    int x;   //a variable to store the number after division

    char binary[10]; //c-string initialized to 10, perhaps that is too many.

    cout << "Enter a number: ";
    cin >> num;

    for (int i = 0; i < 10; i++)
    {
        x = num / 2;    
        cout << x << endl; //this shows that the code is working
        rem = num % 2;
        cout << num << endl; //this also shows the code is working

        char r = (char)rem;   //These two lines of code are 
        strcpy(binary[i], r); //preventing compilation

        cout << binary[i] << endl; // this is diagnostic
        num = x;
    }

    cout << "The number " << num << " is " << binary[5] << " in binary.\n"; 

    return 0;
}

谢谢你们两位,我已经能够完成这项工作(差不多)。 我仍然有一些意想不到的行为,我不确定将阵列初始化到多大,我不认为它会影响太大,但我不确切地知道分级员用来测试的数字有多大。

无论如何,这里是新代码:

#include <iomanip>
#include <iostream>
#include <iomanip>
#include <cstring>

using namespace std;

int main()
{
    int num; //the number a user enters
    int rem; //the remainder, the 1 and 0 of the binary number
    int x;   //a variable to store the number after division

    char binary[5] = {'0', '\0'}; //c-string initialized to 10, perhaps that is too many.

    cout << "Enter a number: ";
    cin >> num;

    for (int i = 0; i < 10; i++)
    {
        x = num / 2;    
        //cout << x << endl; //this shows that the code is working
        rem = num % 2;
        //cout << num << endl; //also shows the code is working

        binary[i] = '0' + rem; //not sure what this is doing, but it works.

        //cout << binary[i] << endl; // this is diagnostic
        num = x;
    }

    cout << "The number " << num << " is " << binary << " in binary.\n";

    return 0;
}

这是输出:

输入一个数字:5 数字0是二进制的1010000000#。

它应显示数字,初始数字,并说出101,没有0&#39;和#符号。

4 个答案:

答案 0 :(得分:1)

strcpy用于复制整个NUL终止的字符串。如果您只想设置一个字符,可以使用=

binary[i] = r;

但是,如果您希望行cout << binary[i]正常工作,或者稍后将binary视为C字符串,则需要存储ASCII数字:

binary[i] = '0' + r;

不要忘记在字符串中添加终止NUL,现在它根本不是C风格的字符串。

答案 1 :(得分:1)

strcpy()的论据是char*,而不是char。第二个参数必须指向以null结尾的字符串,但r只是一个字符。要将字符分配给数组的元素,请执行以下操作:

binary[i] = r;

但是你不想要rem的二进制值,你想要代表那个二进制值的字符。它应该是:

char r = '0' + rem;

为了将binary打印为字符串,您需要为其提供一个空终止符。由于您将10个数字放入字符串中,因此需要声明一个额外的字符来保存终结符,并用零初始化它以使其正确终止。

char binary[11] = {0};

如果你想打印整个字符串,你不应该引用binary[5],你应该打印整个数组:

cout << "The number " << num << " is " << binary << " in binary.\n"; 

答案 2 :(得分:0)

除了已经指出的问题之外,您还会以相反的顺序获得二进制数字。您必须在二进制表示中计算有效数字,并在完成后反转字符。

你没有正确地初始化字符缓冲区,这就是为什么你在打印输出中得到垃圾的原因。

对于缓冲区大小,您需要的字符数与要转换的整数类型中的位数一样多,另外还有一个用于终止&#39; \ 0&#39;,因此对于32位数字,您需要33字符大小的缓冲区。这很重要,因为如果你超出你的缓冲区,就会发生非常讨厌的事情。

还有一点需要注意:我假设你应该转换为字符串表示的数字是无符号的,所以要明确它。下面是一个快速而又脏的实现,其中包含一些最小的错误检查:

char *unsigned_to_binstr (unsigned n, char *binary, int buf_len)
{
  int i, j;

  if (buf_len < 2)
      return NULL;

  i = 0;
  do {
      binary[i++] = '0' + n % 2;
      n /= 2;
  } while (n && i < buf_len);

  for (j = 0; j < i / 2; ++j) {
      char temp = binary[j];
      binary[j] = binary[i-j-1];
      binary[i-j-1] = temp;
  }

  binary[i] = '\0';

  return binary;
}

答案 3 :(得分:0)

在每个人的评论和我自己的研究通过我的教科书后,我能够形成一个有点工作的功能。但是,在这个过程中我开始怀疑垃圾问题,所以我的解决方案..截断!我添加了if子句(尝试考虑循环表示但没有得到任何想法)并且最后我只使用if子句提供的长度并减去1,这应该给出适当的数字位大小。使用我们在课堂上所涵盖的基本c ++知识,这就是我提出的解决方案,但它可能是粗糙和低效的!

我要感谢你们所有人,如果不适合你的话,我无法克服这个问题!

这是我粗略的最终修订版:

//sample integer to binary

#include <iostream>

using namespace std;

int main()
{
    int num; //the number a user enters
    int rem; //the remainder, the 1 and 0 of the binary number
    int x;   //a variable to store the number after division
    int l; //length of c-string function

    cout << "Enter a number: ";
    cin >> num; //user input

    if ((num == 1) || (num == 0))  // the following 17 lines of code are to truncate the string       size.
        l = 2;
    if ((num > 1) && (num < 4))
        l = 3;
    if ((num >= 4) && (num <= 7))
        l = 4;
    if ((num >= 8) && (num <= 15))
        l = 5;
    if ((num >= 16) && (num <= 31))
        l = 6;
    if ((num >= 32) && (num <= 63))
        l = 7;
    if ((num >= 64) && (num <= 127))
        l = 8;
    if ((num >= 128) && (num <= 255))
        l = 9;
    if ((num > 255)) 
        cout << "This number is too large for this string\n"; // I don't think the binary sequence should be larger than 16 bits.

    char binary[l];  //c-string initialized to size according to the truncation rules above

    for (int i = l - 1; i > 0; i--) //goes in reverse order, as binary counts from bottom to top.
    {
        x = num / 2;    
        rem = num % 2;
        num = x;

        binary[i] = '0' + rem; // added an
    }



    for (int i = 0; i <= l-1; i++)
    {
        cout << binary[i];
    }

    cout << " in binary.\n";

    return 0;
}