gpt4 book ai didi

C 二进制字符串编程

转载 作者:行者123 更新时间:2023-11-30 21:00:23 25 4
gpt4 key购买 nike

我有一个 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;
}

最佳答案

不要使用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 );
}

关于C 二进制字符串编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com