如何使用 sscanf 扫描由 `/` 分隔的两个字符串?

How scan two strings separated by `/` using sscanf?

我想使用 sscanf 扫描到由 / 分隔的单独字符串,但它不起作用。它适用于 space.

例如,我想将字符串 50%/60% 分成两个字符串,如 50% 和 60%。

你可以看看代码here:

#include <iostream>
using namespace std;

int extract_break_rewrites(int *m, int *n, const char *arg)
{
    char m_str[10];
    char n_str[10];
    int err;

    int count = sscanf(arg, "%s %s", n_str, m_str);
    printf("%s %s %d\n",n_str, m_str,count);
    if (count == 0) {
        count = sscanf(arg, "/%s", m_str);
        if (count == 0) {
            *m = 0;
            *n = 0;
            return -1;
        }
        if (sscanf(m_str, "%d%%", m) != 1) 
            return -1;
    }
    else if (count == 1) {
        if (sscanf(n_str, "%d%%", n) != 1) 
            return -1;
    }
    else if (count==2) {
        if (sscanf(n_str, "%d%%", n) != 1) 
            return -1;
        if (sscanf(m_str, "%d%%", m) != 1) 
            return -1;
    }
    return 1;
}

int main() {
    int n,m;
    const char * command = "50% 60%";
    if (extract_break_rewrites(&m,&n,command)!=-1)
        cout<<"Successful. The values of m and n are "<<m<<" and "<<n<<", respectively.\n";
    else
        cout<<"There was error in processing, may be input was not in the correct format.\n";
    return 0;
}

您无需担心代码的作用,重要的行是 10、11 和 main 函数。

使用扫描集

char a[100];
char b[100];
scanf("%[^/]/%s", a, b);

这会扫描所有内容,直到获得 /,然后它开始并读取字符串。

尝试以下操作(假设来自标准输入):

scanf("%[^/]/%s");

如果从缓冲区读取,则使用 sscanf(buf, ...);

问题是 scanf%s 假定字符串后跟 space。此方法指示 scanf 查找由 / 分隔的字符串,然后将其余部分作为单独的字符串进行匹配。

编辑:不小心将 / 放入扫描字符串

您也可以使用 std::strings 和他们的工具来达到相同的结果:

#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::stoi;

bool extract_break_rewrites(int &m, int &n, const string &arg) {
    // find position of %/ in the string
    string::size_type pos_first = arg.find("%/");
    // check if the return value is valid (the substring is present and there
    // is something else first)
    if ( pos_first == string::npos  ||  !pos_first )    // wrong input
        return false;

    string::size_type pos_2 = pos_first + 2,
                      pos_last = arg.find("%", pos_2);
    if ( pos_last == string::npos  ||  pos_last == pos_2 )  
        return false;

    try {
        m = stoi(arg.substr(0, pos_first));
        n = stoi(arg.substr(pos_2, pos_last - pos_2));
    }
    // invalid argument or out of range
    catch (...) {
        return false;
    }

    return true;
}

int main() {
    int n = 0, m = 0;
    string command = "150%/60%";

    if ( extract_break_rewrites(m, n, command) )
        cout << "Successful. The values of m and n are "
             << m << " and " << n << ", respectively.\n";
    else
        cout << "There was error in processing, "
             << "maybe input was not in the correct format.\n";

    return 0;
}