#define MAXLEN 25
typedef struct{
char ch[MAXLEN];
int length;
}SString;
Substring(SString &Sub,SString S,int pos,int len){
if(pos+len-1>S.length)return false;
for(int i=pos;iSub.ch[i-pos]=S.ch[i];
Sub.length=len;}
printf("%s",Sub.ch);
}
int main(){
SString Sub;
SString S;
for(int i=0;i"%c",&S.ch[i]);
}
Substring(Sub,S,1,4);
}
修改如下,改动处见注释,供参考:
#include <stdio.h>
#define MAXLEN 25
typedef struct {
char ch[MAXLEN];
int length;
}SString;
void Substring(SString& Sub, SString S, int pos, int len) { //修改
int i; //修改
if (pos + len > S.length || pos < 0) return; // false; 修改
for (i = pos; i < pos + len; i++)
{
Sub.ch[i - pos] = S.ch[i];
}
Sub.ch[i - pos] = '\0'; //修改
Sub.length = len; //修改
printf("%s", Sub.ch);
}
int main() {
int i; //修改
SString Sub;
SString S;
scanf("%s", S.ch); //修改
for (i = 0; S.ch[i]; i++); //修改
S.length = i; //修改
//{
//scanf("%c", &S.ch[i]);
//}
Substring(Sub, S, 1, 4);
return 0;
}
Substring 函数定义有问题,没有返回值,要么你就定义 void
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#define MAXLEN 10
typedef struct{
char ch[MAXLEN];
int length;
}SString;
void Substring(SString &Sub,SString S,int pos,int len){
if(pos+len-1 > S.length)
return;
int i;
for(i=pos;i<pos+len;i++)
{
Sub.ch[i-pos]=S.ch[i];
Sub.length=len;
}
Sub.ch[i-pos] = '\0';
}
int main(){
SString Sub;
SString S;
scanf("%s", S.ch);
S.length = sizeof(S.ch) - 1;
Substring(Sub,S,1,4);
printf("%s", Sub.ch);
}