Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

printf - How to get specific adjacent characters of a string and add it to an another string in C

I have an abstract concept to use a for-loop to get specific adjacent characters of a string and add it to a stack, basically take all the constants of a string expression and add it to the stack separately; For example string: "1111+(2222-3333)" would be put in to the stack like "1111","2222", and "3333". I have a code below to start with that abstract concept but first trying it out with a simple one, and unfortunately it doesn't output the desired result of copying the specific adjacent characters.

char expression[20]={""},sub[20]={""};
    scanf("%[^
]%*c",&expression);
    sub[15]=expression[15];
    sub[16]=expression[16];
    sub[17]=expression[17];
    sub[18]=expression[18];
    printf("%c %c %c %c
",sub[15],sub[16],sub[17],sub[18]); //to check if copied successfully
    printf("sub= %s",sub); //doesnt print expected output
question from:https://stackoverflow.com/questions/65872027/how-to-get-specific-adjacent-characters-of-a-string-and-add-it-to-an-another-str

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After this declaration

char expression[20]={""},sub[20]={""};

all elements of the array sub contain zeroes.

You changed elements of the array starting from the position 15

sub[15]=expression[15];
sub[16]=expression[16];
sub[17]=expression[17];
sub[18]=expression[18];

The elements before the position still store zeroes.

So this call of printf

printf("sub= %s",sub);

assumes that the array contains an empty string because it first character is the terminating zero character ''.

Instead you could write

printf("sub= %s",sub + 15 );

Or you could change the assignments like

sub[0]=expression[15];
sub[1]=expression[16];
sub[2]=expression[17];
sub[3]=expression[18];

and then use

printf("sub= %s",sub);

Pay attention to that the second argument of this call of scanf

scanf("%[^
]%*c",&expression);

is incorrect. You have to write

scanf("%[^
]%*c",expression);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...