希望输入 - >
"Enter a word: program"
"Enter a postion to know where to start cutting: 2"
"Enter the following quantity to end up: 4"
希望输出 - >
ogra
这是我的代码,但我不知道如何将值插入到不同的数组
#include <stdio.h>
#include <string.h>
int main (){
char word[100], cutword[50];
int on, off, i, j;
printf("Entra a word: ");
gets(word);
printf("Enter a postion to know where to start cutting: ");
scanf("%d", &on);
printf("Enter the following quantity to end up: ");
scanf("%d", &off);
for (i = 0; i<strlen(word); i++){
if (i >= on && i <= off) ¿cutword[]? = word[i];
}
for (j = 0; j<strlen(cutword); j++){
printf("%c", cutword[j]);
}
}
答案 0 :(得分:3)
int k = 0;
int l = on + off;
for (i = on; i < l; i++){
cutword[k++] = word[i];
}
for (j = 0; j < k; j++){
printf("%c", cutword[j]);
}
在这些循环之前添加一些额外的if
来验证输入并检查数组边界。
答案 1 :(得分:0)
// if there is enough room in the buffers
if( strlen(word) > off) {
// copy from word + (offset)
// to cutword[0]
// off number of characters
memcpy(cutword, word + on, off );
}
多数民众赞成,如果你想从位置2获得4个字符
你的代码获得第2位到第4位。
答案 2 :(得分:0)
问题在于您的第一个for
循环。仅在off + on
之后对其进行迭代,并将¿cutword[]? = word[i];
部分替换为cutword[j++] = word[i];
试试这个
for (j = 0; i = 0; i < off + on; i++){
if (i >= on && i <= off)
cutword[j++] = word[i];
}
cutword[j] = '\0';
puts(cutword);