I was wondering how I can copy a part of a string to another one, so I checked this web to see if I could get an answer, and I did: How can I copy part of another string in C, given a starting and ending index
However, when I use this
strncpy(dest, src + beginIndex, endIndex - beginIndex);
on my code, it does not work. Why? I think I have added the indexs properly.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#define MAX 15
int main()
{
int j=0;
int i;
char RPNarray[MAX];
printf("Enter the RPN");
fgets(RPNarray,MAX,stdin);
int t=strlen(RPNarray);
double RPN[t][2];
for(i=0;i<=t;i++)
{
if(isspace(RPNarray[i]))
{
i=i+1;
}
else if (isdigit(RPNarray[i]))
{
int q,h;
q=i;
for (h=i;isdigit(RPNarray[h]);h++)
{
h=h+1;
}
int r;
double u;
r=h-q;
char number[r];
printf("%s ", RPNarray);
strncpy(number,RPNarray + q,h - q);
printf ("%s\n",number);
u=atof(number);
printf("%lf.\n",u);
RPN[j][0]=0;
RPN[j][1]=u;
i=i+1;
j=j+1;
}
}
int b;
for (b=0;b<=j;b++)
{
printf("%lf %lf \n",RPN[b][0],RPN[b][1]);
}
}
r
is the number of digits of the number, q
the position of the first digit of the number and h the first position after the number that is not a number.
This program should print the RPN matrix as the code says.
(0,(first number we introduce via stdin)
(0,(second number we introduce via stdin)
(0,(third number we introduce via stdin)
I have also added more prints to see where is the problem, and as you can see, the second print is not printed as it should.
If the input is:
56 6
The output is:
56 6
56OT?
56.000000.
vector 0.000000 56.000000
vector 0.000000 0.000000
What can I do so the output is:
56 6
56
56.000000.
56 6
6
6.000000.
vector 0.000000 56.000000
vector 0.000000 6.000000
Thank you