c - C 中的字符串 : giving some logical error

标签 c

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<stdbool.h>
char output[17]={0};
const char* change_mac(char ch[100])
{
    int i = 0;
    int k = 0;

    bool flag = false;
    while(i < strlen(ch)) 
    {
        flag = false;
        int j = 0;
        while (j < 2)
        {
            if(ch[i] == ':' || strlen(ch) == i ) 
            {
                if(k != 0) 
                {
                    char temp = output[k-1];
                    output[k-1] = '0';
                    output[k] = temp;
                }
                flag = true;
            } 
            else 
            { 
                output[k] = ch[i];
            }
            i++;
            j++;
            k++;
        }
        if(i < strlen(ch) && memchr(ch, ':', strlen(ch)))
        {
            output[k] = ':';
            output[k+1] = '\0';
        }
        else{
            output[k] = ch[i];
        }
        k++;
        if(!flag) 
        {
            i++;
        }
    }

    output[k-1] = 0;
   return output;
}



int main(int argc,char **argv)
{
char name[]="";
char ch[100] = "0:0:0:0:0:0";

if(sscanf(argv[1],"%s",ch) == 1)
{
  name=change_mac(ch);
} 
return 0;
}

/我想获取 MAC,因为 CMD 行争论将其更改为正确的格式并将其存储到这个“名称”变量中所以我可以在这里进一步使用它它显示了一些类型转换错误/

/* 执行:./a.out 0:c:f4:dr:4r:1 */

最佳答案

您忘记在 output[] 的末尾添加 '\0'。在 printf("%s\n",output); 之前添加如下代码:

output[k-1] = '\0';    

接下来,
我不太确定,但是对于第二个功能,如果下面的代码改变你:

if(i !=sizeof(ch))
{
    output[k] = ':';
}

到后面(仅当 ch[] 中存在时才添加 ':')

if(i !=sizeof(ch) && memchr(ch, ':', sizeof(ch)))
{
     output[k] = ':';
}
else{
    output[k] = ch[i];
}  

并包含一个头文件string.h

试试吧!如果您还有其他疑问,请告诉我。

但是是的,它不像您想要的“尝试并捕获或错误处理”

编辑
我正在修复您在我的回答中评论的错误:
printf("%s\n",output);

之前添加以下代码
output[k-1] = 0;
if(memchr(ch, ':', sizeof(ch))==NULL){
        output[k-2] = 0;
} 

cation:这样的错误修复方法不是很好,建议重写代码

关于c - C 中的字符串 : giving some logical error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14433407/

相关文章:

c++ - 启动 n 次 启动配置 C/C++

c - 使用不同的宏多次包含一个文件

c - "gcc -o test test.c; test"不产生任何输出

c - c 中的 strtok 有问题

c - 使用循环将字符添加到 c 中的 "strings"数组时遇到问题?

c - 我应该使用什么文档工具来处理这个问题?

c - 帮助 scanf 在 Big Endian 系统上表现不同

c - strtok() 问题获取字符串的第一个标记

c - 从视频文件中提取帧作为 rgb 数组

c - 添加到 FLT_MAX 中导致溢出的最小数字