#include <string.h>
#include <stdio.h>
#define bool int
#define true 1
#define false 0
static bool is_digit(char c){
return c > 47 && c < 58;
}
static bool is_all_digit(char *s){
while(s){
if(is_digit(*s++)){
continue;
}
return false;
}
return true;
}
int main(){
char *s = "123456";
int i;
printf("len = %d\n", strlen(s));
for(i = 0; i<strlen(s); ++i){
printf("%c : %s\n", *s, is_digit(*s++)? "true" : "false");
//printf("%c : %s\n", s[i], is_digit(s[i])? "true" : "false");
}
return 0;
}
我想实现评论部分的功能。 但结果如下:enter image description here
以3结尾,4~6消失。 我的运行环境是win10 gcc 6.3.0
最佳答案
这存在很多问题。
您
printf
使用了错误的格式字符串。 Use%zu
for asize_t
, not%d
。您的
printf
具有未定义的行为,因为同一表达式中有*s
和*s++
,它们之间没有 sequence point .您在循环的每次迭代中重新计算
strlen(s)
,并且该值不断下降,因为您不断增加s
。在开始之前,我会将strlen(s)
缓存到名为n
(或类似变量)的变量中,因为n
不会改变。
我的编译器警告我除了第三个错误之外的所有错误。
该程序有效:
#include <string.h>
#include <stdio.h>
#define bool int
#define true 1
#define false 0
static bool is_digit(char c){
return c > 47 && c < 58;
}
int main(){
const char *s = "123456";
size_t i;
const size_t n = strlen(s);
printf("len = %zu\n", n);
for(i = 0; i<n; ++i){
printf("%c : %s\n", *s, is_digit(*s)? "true" : "false");
s++;
}
return 0;
}
(live demo)
您也可以完全跳过 strlen
并仅查找空终止符:
#include <string.h>
#include <stdio.h>
#define bool int
#define true 1
#define false 0
static bool is_digit(char c){
return c > 47 && c < 58;
}
int main(){
const char *s = "123456";
while (*s) {
printf("%c : %s\n", *s, is_digit(*s)? "true" : "false");
s++;
}
return 0;
}
(live demo)
关于c - *s++ 中发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959809/