use*_*292 1 c c++ scanf format-specifiers
我在我的项目中使用sscanf将字符串从源缓冲区复制到目标缓冲区.例如:
char* target;
target = (char*)malloc(100 * sizeof(char));
char* source = "Hello World";
sscanf(source, "%[^\t\n]", target); // trying to copy "Hello World" into target.
printf("%s\n", target);//this will print "Hello World".
Run Code Online (Sandbox Code Playgroud)
但是这种编码风格的方式是不被接受的.我的经理要我做的是:
sscanf(source, "%11[^\t\n]", target); // NOTE: I've written "%11". here, 11 == length of hello world.
Run Code Online (Sandbox Code Playgroud)
这意味着,他希望我也提供格式说明符.(在这种情况下为%11).
但是,问题是源的长度可能不同,我不知道如何为每个变长字符串编写正确的格式说明符.
使用:
sscanf(source, "%*[^\t\n]", maxlen, target)
Run Code Online (Sandbox Code Playgroud)
其中maxlen是你想要阅读的大小.
似乎没有简单的方法可以为sscanf(或任何兄弟姐妹)的格式字符串采用输入字符串的任意最大长度.该建议是基于printf正交scanf,事实证明并非如此.
你会发现你不得不使用更好的运气strtok,要么strncpy或strdup复制令牌.
但是,由于它标记了C++,为什么不使用:
std::stringstream ss(source);
std::string target;
getline(ss, target, "\t");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
709 次 |
| 最近记录: |