【问题标题】:fill an array with Int like a Char; C++, cin object像 Char 一样用 Int 填充数组; C++,cin 对象
【发布时间】:2011-11-25 01:26:36
【问题描述】:

这是一个非常简单的问题;第一次发布海报,长期观看。

这是我写的二进制到十进制转换器:

#include <iostream>
#include <cmath>
using namespace std;
const int MAX = 6;
int conv(int z[MAX], int l[6], int MAX);

int main()
{
    int zelda[MAX];
    const int d = 6;
    int link[d];

    cout << "Enter a binary number: \n";  
    int i = 0;
    while (i < MAX && (cin >> zelda[i]).get())  //input loop
    {
        ++i;
    }   

    cout << conv(zelda, link, MAX);

    cin.get();
    return  0;
}

int conv(int zelda[MAX], int link[6], int MAX)
{   
    int sum = 0;
    for (int t = 0; t < MAX; t++)
    {
        long int h, i;
        for (int h = 5, i = 0; h >= 0; --h, ++i)
            if (zelda[t] == 1)
                link[h] = pow(2.0, i);
            else
                link[h] = 0;
            sum += link[t]; 
    }
    return sum;
}

由于处理输入循环的方式,我必须在每次输入数字后按回车键。我还没有添加任何错误更正(我的一些变量是模糊的),但想输入一个二进制,比如 111111 而不是 1 enter、1 enter、1 enter 等来填充数组。我对任何技术和其他建议持开放态度。也许将其输入为字符串并将其转换为 int?

我会继续研究。谢谢。

【问题讨论】:

  • 你的变量命名是最有趣的。
  • 你的整个输入逻辑非常晦涩难懂。您为什么不简单地读取 one 字符串,预计仅包含 1s 和 0s,然后将其转换?
  • 最佳变量命名法,EVAR :)(必须发表此评论 :))
  • 感谢各位程序员。老实说,我没有多想-_-
  • 你应该在 masterSword 中返回你的总和。

标签: c++


【解决方案1】:

要读取数据,see this related question(并将文件流替换为std::cin)。

要转换,你可以做一些简单的事情:

unsigned int convert(const std::string & s)
{
  // maybe check that s.size() <= CHAR_BIT * sizeof(unsigned int)

  unsigned int result = 0;

  for (std::string::const_reverse_iterator rit = s.rbegin(), rend = s.rend(); rit != rend; ++rit)
  {
    result *= 2;

    if (*rit == '1') ++result;

    else if (*rit != '0') { /*error!*/ return -1; }
  }

  return result;
}

【讨论】:

  • 我将阅读该链接并从另一个角度了解如何解决此问题。似乎以字符串形式输入是最好的方法。
【解决方案2】:

你可以这样读取一个 int 并解析它:

int number = 0;

cin >> number;
int i = 0;
while(i < MAX)
{
    if(number > 0)
    {
        zelda[i] = number % 10; // or you can switch to zelda[MAX-(i+1)]
        number = number/10;
    else
    {
        zelda[i] = 0;
    }
    i++;
}

编辑:
请注意,这种转换是小端格式,这意味着如果您输入 int '100',zelday 将被填充为 '001'。

EDIT2:
如果您想从字符串中获取它,请执行此操作,假设 zelda 的大小与 str 相同:

string str ("111000");
int i;
for (i=0; i < str.length(); i++)
{
    zelda[i] = (str[i] - '0');
}

为什么会这样:
char 列表中表示的数字是连续的(在这种情况下为 int ASCII),即数字零表示为 48,数字一表示为 49,依此类推。所以当你减去 '0' 的表示时,你会得到实际的数字。

【讨论】:

  • 我喜欢这种方法,但我可能不得不解决 endian 格式。肯定有一些想法。
  • 切换评论版本zelda[MAX-(i+1)]而不是zelda[i],然后你切换。
  • 这一切都很好。我如何提高你的声誉?我不知道我是否可以在我的低级别。
  • 只需点击向上箭头为答案点赞,然后点击V标记接受,所有用户都可以投票并接受答案。
  • 啊我刚才试过了,但我需要 15 个代表。还在摸索这个论坛的内部运作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 2013-03-10
  • 2010-09-27
相关资源
最近更新 更多