|
正确: #include <string.h>
#include <iostream>
using namespace std;
void main()
{
char s[] = "192.168.0.1";
char *delim = ".";
char *p;
p=strtok(s, delim);
printf("%s ", p);
while((p = strtok(NULL, delim)))
printf("%s ", p);
printf("\n");
}
错误: #include <string.h>
#include <iostream>
using namespace std;
void main()
{
char *s = "192.168.0.1";
char *delim = ".";
char *p;
p=strtok(s, delim);
printf("%s ", p);
while((p = strtok(NULL, delim)))
printf("%s ", p);
printf("\n");
}
不知道错误的原因! |
|
| 5分 |
char *s = “192.168.0.1”;
这句必须写成: 编译器不报错,是历史的原因。 |
|
strtok这个函数会更改第一个参数的内容
|
|
| 10分 |
而char *s = “192.168.0.1”;中的s指向了一个常量字符串,其所在的内存是不能被更改的
char s[] = “192.168.0.1”;这里的s是用后面的常量字符串去初始化s所在的内存区域,这个区域是可以更改的 你可以通过调试来查看 |
| 5分 |
#pragma comment(linker,"/SECTION:.rdata,RW") //加这句可以让常量区可写,后果自负! |
|
仅供参考:
#include <stdio.h>
int main() {
int IP[4];
int i;
char c;
printf("请输入一个ip地址:");fflush(stdout);
while (1) {
rewind(stdin);
if (5==scanf("%d.%d.%d.%d%c",&IP[0],&IP[1],&IP[2],&IP[3],&c)) {
if (0<=IP[0] && IP[0]<=255
&& 0<=IP[1] && IP[1]<=255
&& 0<=IP[2] && IP[2]<=255
&& 0<=IP[3] && IP[3]<=255
&& ""\n""==c) {
break;
} else printf("输入的ip地址格式不对!\n请重新输入:\n");
} else printf("输入的ip地址格式不对!\n请重新输入:\n");
}
for (i=0;i<4;i++) {
printf("IP[%d]=%d\n",i,IP[i]);
}
return 0;
}
|
|
|
感谢
|
|