Problem with substring program

pratap singh, upendra

pratap singh, upendra

@pratap-singh-6xlmve Oct 26, 2024
hello friends,

I wrote a c program to perform the substring operation on the string str[100]. This program was to take the position index pos and the number of characters len that needs to be printed on the screen. variable length stores the length of the string str[100].

Although I am getting the correct output from this program yet, I get additional characters after my output text. Please help me with this situation.

Here is the program that I have coded:-

#include<stdio.h>//extra ouput
void main()
{
char str[100], subs[100];
int len,length = 0, pos,i = 0,j = 0;
printf(" enter the string\n");
gets(str);
printf(" enter the position\n");
scanf("%d", &pos);
printf(" enter the length\n");
scanf("%d", &len);
for( i = 0; str != '\0'; i++)
length++;
i=0;
if((pos+len-1) > length)
printf("invalid query terminating...\n");
else
{
i = pos;
for(j = 0; j<len; j++)
{
subs[j] = str;
i++;
}
}
printf("\n\n displaying the result\n\n");
i = 0;
puts(subs);
}

this program produces extra characters like ?^ at the end of the output text.

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Shalini051

    Shalini051

    @shalini051-dAmwVY May 7, 2013

    Hi,
    You have not terminated the substring(subs) after extracting it from the original string(str).Thats why the junk characters.....
  • rahul69

    rahul69

    @rahul69-97fAOs May 8, 2013

    proffy
    hello friends,
    this program produces extra characters like ?^ at the end of the output text.
    First of all, it is better to put your code in [ code ] tags as it helps in reading the code,
    Now coming to your code:
    You should add a null character after the creation of substring.
    This should solve your problem, but if u still face some problem, we are happy to help👍😁...