【问题标题】:C string programming binaryC字符串编程二进制
【发布时间】:2017-06-05 15:45:46
【问题描述】:

我有一个接受字符串输入的 c 程序我想检查这些输入是否是二进制值我该怎么做?

例如,如果用户输入“1001”我怎样才能检查它是否是二进制文件尽量不使用指针请在c中也这样做也不要使用数学库

@Mywork 到目前为止 我将字符串转换为整数并使用 atoi 函数 这是我检查整数的函数

@程序重新解释 我正在使用 scanf 函数接收两个输入,并将它们存储为字符串,用户应该输入两个二进制数。然后我想检查并确保这些数字中的每一个都是二进制的。下面是一些例子

INput: 101001 100101
Both Stored As String.
Output:function checks and see thats they are both binary

     That is a correct way I want it to run. Here is another example
   Input:1001hshds101 100101
   Both stored as String
   Output: Checks both strings and knows that the first string is wrong







//SOme of my work (ignore this for the most part)
int binCheck(long long int input){
      int dv;
       while(input! = 0){
        dv = input%10;
       if(dv>1){
           return 0;
          }
       input = input/10;
    }
    return 1;
    }

【问题讨论】:

  • 这听起来像是另一个作业。你都尝试了些什么?向我们展示一些代码,我们将提供帮助
  • @SeekAddo 刚刚添加了一些代码。
  • 我想这里“二进制”的定义是一个十进制表示只包含0和1的数字,如果我错了,请纠正我。您的 binCheck 函数对我来说似乎是正确的。那么真正的问题在哪里?
  • @MichaelWalz 是的,这是正确的,问题是如果用户输入“101hsjfh”它不起作用。
  • @donaldTheProgrammer 请向我们展示相关代码。但无论如何,从我从你的描述中了解到,这是很正常的,atoi 在第一个非数字数字处停止,所以如果你的字符串是"101hsf"atoi 将简单地返回 101,忽略"hsf"。为什么不直接扫描字符串并直接检查 '1' 和 '0' 以外的字符?这段代码会更短,binCheckatoi 都不会,它会做你想做的事。

标签: c string binary


【解决方案1】:

不要使用atoi()。只需遍历字符串的每个字符并确保每个字符都是“0”或“1”。下面的例子。

#include <stdio.h>
#include <string.h>

int isBinary( char *value );


int isBinary( char *value )
{
    int i;
    int bIsBinary = 0;
    int len;

    bIsBinary = 1;

    len = strlen( value );
    for( i = 0; i != len; i++ )
    {
        if ( value[i] != '0' && value[i] != '1' )
        {
            bIsBinary = 0;
            break;
        }
    }
    return( bIsBinary );
}


int main (void)
{
    char *value = "101a001";
    int isBin;

    isBin = isBinary( value );
    printf( "[%s] is Binary::%s\n", value, (isBin) ? "true":"false" );

    return( 0 );
}

【讨论】:

  • 你能把长度弄一次吗?即把int len = strlen(value);放在循环上面,然后for(i=0;i&lt;len;i++)...
  • @ryyker 是的,这样做是合理的。
  • 你能把它作为main以外的函数来做吗?
  • @donaldTheProgrammer 当然。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-26
  • 2017-02-23
  • 2014-08-03
  • 2011-07-11
  • 1970-01-01
相关资源
最近更新 更多