简体   繁体   中英

How to deal with the return value which are new line and special symbol in C?

Here is a newbie's question, I have a return value which have two new line and some special symbol.

But I only want to get the specific part of above-mentioned value.

There is a simple example that base on my code.

When I use C to execute the command, I will get the format of return value like...

Code:

fp = popen("cfg get+myvalue", "r");
fgets(buf, sizeof(buf), fp); //First Line
fgets(buf, sizeof(buf), fp); // Sec Line

Return Value:

get+myvalue
+Value: "123456789"

For now, I had already try strtok_r(). It actually can divide into two parts (+Value: & "123456789").

But I wanna know is there any more efficient way to get 123456789 without double quote?

I only want to fetch the part of 123456789. Is there any good solution to solve this issue?

Any advice would be appreciated.

Is very easy using strchr and strrchr :

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[] = "+Value: & \"123456789\"";
    char *start = NULL, *end = NULL;

    start = strchr(str, '"');
    if (start != NULL)
    {
        end = strrchr(++start, '"');
        if (end != NULL)
        {
            *end = '\0';
        }
    }
    if (start && end)
    {
        puts(start);
    }
    return 0;
}

Output:

123456789

like that

#include <stdio.h>
#include <stddef.h>
#include <iostream>

int main(int argc , char *argv[])
{
    char t[] = R"(vte
ok "lp")", x, q[200]={0};
    sscanf(t,"%*[^\"]%*c%[^\"]" ,q);
    std::cout << q << std::endl;
}

warning: non-C code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM