(C语言)代码学习||2024.2.6||题目是codewars上的【 IP Validation】

C语言 #sscanf #代码学习 #codewars

题目链接:IP Validation | Codewars
代码如下:

#include <stdio.h>
int is_valid_ip(const char *addr)
{
unsigned n[4], i, nc;
// Must be 4 integers separated by dots:
if( sscanf(addr, "%d.%d.%d.%d%n", &n[0], &n[1], &n[2], &n[3], &nc) != 4 )
return 0;
// Leftover characters at the end are not allowed:
if( nc != strlen(addr) )
return 0;
// Leading zeros and space characters are not allowed:
if( addr[0] == '0' || strstr(addr, ".0") || strchr(addr, ' ') )
return 0;
// Values > 255 are not allowed:
for(i=0; i<4; i++)
if( n[i] > 255 )
return 0;
return 1;
};

首先sscanf()的用法,普通的scanf是从标准输入stdio中获取输入,并通过字符串参数中的格式化占位符来将输入中的字符串内容转化为对应类型的数据,并存通过后面变量列表中传入的地址参数将数据存入到相应的变量中。

sscanf()则只是将输入从标准输入获取改为从某一字符串中获取。菜鸟教程的说法是

C 库函数 **int sscanf(const char str, const char format, ...) 从字符串读取格式化输入。

这个题中是想实现类似下面的效果:

char str[]= "123.34.33.21";
int a[4], b;
sscanf(str, "%d.%d.%d.%d%n", &a[0], &a[1], &a[2], &a[3],&b);
for (int i = 0; i < 4; i++) {
printf("%d ", a[i]);
}
printf("\n%d", b);
/*输出
123 34 33 21
12
*/

题目中sscanf里还有个%n,并将它的值给了nc。之后将nc的值与字符串addr的长度进行了比较。
%n的作用是获取目前已打印的字符个数,并传递给后面变量列表中对应的变量,正常来说%n是在print()中使用的:

#include <stdio.h>
int main()
{
int val;
printf("blah %n blah\n", &val);
printf("val = %d\n", val);
return 0;
/*
blah blah
val = 5
*/
}

但不知道为什么,我自己在VS中运行上面的代码会报错
但在scanf()sscanf()中使用%n就没问题
用到scanf()sscanf()中的作用就是计算已处理的输入字符的个数,并不仅仅是成功传入变量的字符的个数:

#include <stdio.h>
int main() {
char str[]= "123.34.33.21";
int a[4], b;
sscanf(str,"%d.%d.%d.%d%n", &a[0], &a[1], &a[2], &a[3],&b);
for (int i = 0; i < 4; i++) {
printf("%d ", a[i]);
}
printf("\n%d", b);
/*输出
123 34 33 21
12
*/
char str2[]= " 123.34.33.21";
int a[4], b;
sscanf(str2,"%d.%d.%d.%d%n", &a[0], &a[1], &a[2], &a[3],&b);
for (int i = 0; i < 4; i++) {
printf("%d ", a[i]);
}
printf("\n%d", b);
/*输出
123 34 33 21
13
*/
}

sscanf()本身也有返回值,它会返回存入值成功的变量的个数。

之后排除了数字以0开头的问题

  • char *strstr(const char *haystack, const char *needle)函数,该函数返回在 haystack 中第一次出现 needle 字符串的位置,如果未找到则返回 null。
#include <stdio.h>
#include <string.h>
int main() {
const char haystack[20] = "RUNOOB";
const char needle[10] = "NOOB";
char *ret; ret = strstr(haystack, needle);
printf("子字符串是: %s\n", ret);
//子字符串是: NOOB
return(0);
}
posted @   Kazuma_124  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示