2

Wished Input ->

"Enter a word: program"
"Enter a postion to know where to start cutting: 2"
"Enter the following quantity to end up: 4"

Wished Output ->

ogra

This is my code, but I don't know how to insert values into a different array

#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]);
    }

}
1
  • What is that ¿cutword[]? Commented Nov 23, 2013 at 19:45

3 Answers 3

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]);
}

Put some additional if to validate the input and check array boundaries before these loops.

Sign up to request clarification or add additional context in comments.

Comments

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 ); 
}

thats if you want from position 2 get 4 characters

your code gets position 2 to position 4.

2 Comments

and without a a prepared function how would it be?
@frankie3 you for loop only considers on until off or word[2] through word[4] .. if you replace the for loop in your code with memcpy it will move all 4 character at one time as opposed to one ata time.
0

Problem is with your first for loop. Iterate it only up to off + on and replace your ¿cutword[]? = word[i]; part with cutword[j++] = word[i]; Try this

for (j = 0; i = 0; i < off + on; i++){
    if (i >= on && i <= off)
        cutword[j++] = word[i];
}
cutword[j] = '\0';
puts(cutword);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.