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

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

本文关键字:字符串 两个 分隔 sscanf 何使用 扫描      更新时间:2023-10-16

我想使用sscanf扫描以分离由/分隔的字符串,但它不起作用。它与空间配合得很好。

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

你可以在这里查看代码:

#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 %dn",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函数。

尝试以下操作(假设来自stdin):

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

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

问题是scanf%s假定字符串后面跟一个空格。这种方法指示scanf查找由/分隔的字符串,然后将其余字符串作为单独的字符串进行匹配。

EDIT:扫描字符串中的/意外丢失

使用扫描集

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

这会扫描所有内容,直到得到/,然后启动并读取字符串。

您也可以使用std::string及其设施来实现相同的结果:

#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;
}