C++ cin vs. C sscanf
C++ cin vs. C sscanf
所以我用C写的,所以sscanf扫描s,然后丢弃它,然后扫描d并存储它。因此,如果输入为"Hello 007",则扫描Hello但丢弃,007存储在d中。
static void cmd_test(const char *s)
{
int d = maxdepth;
sscanf(s, "%*s%d", &d);
}
所以,我的问题是我怎么能做同样的事情,但在c++ ?可能使用stringstream?
#include <string>
#include <sstream>
static void cmd_test(const char *s)
{
std::istringstream iss(s);
std::string dummy;
int d = maxdepth;
iss >> dummy >> d;
}
您不能真正提取到匿名字符串中,但您可以创建一个dummy并忽略它:
#include <string>
#include <istream>
// #include <sstream> // see below
void cmd_test(std::istream & iss) // any std::istream will do!
{
// alternatively, pass a `const char * str` as the argument,
// change the above header inclusion, and declare:
// std::istringstream iss(str);
int d;
std::string s;
if (!(iss >> s >> d)) { /* maybe handle error */ }
// now `d` holds your value if the above succeeded
}
注意,提取可能会失败,因为我输入了条件。这取决于你在出现错误时怎么做;c++要做的事情是抛出一个异常(尽管如果你的实际函数已经传达了错误,你可能只需要return
一个错误)。
使用例子:
#include <iostream>
#include <fstream>
int main()
{
cmd_test(std::cin);
std::ifstream infile("myfile.txt");
cmd_test(infile);
std::string s = get_string_from_user();
std::istringstream iss(s);
cmd_test(iss);
}
怎么样:
#include <string>
#include <sstream>
static void cmd_test(const std::string &s)
{
int d = maxdepth;
std::string dont_care;
std::istringstream in(s);
in >> dont_care >> d;
}
相关文章:
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 用C++中的sscanf赋值
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 数据成员SFINAE的C++17测试:gcc vs clang
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 正在VS调试器中监视映射条目
- Confusion: decltype vs std::function
- 将IBM Rhapsody模型集成到VS 2019中
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 使用VS Code和CMake Tools运行自定义命令
- 具有结构成员char数组的sscanf
- 修改 VS Code 中的默认C++代码段
- 如何使用c++在VS 2019上运行SQL查询
- vs 2015 constexpr变量不恒定,但与2019相比还好吗
- 完美前进使用 std::forward vs RefRefCast
- 从VS 2015更新3更新到VS2015更新3 d后浮点计算行为不同的原因
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- C++ cin vs. C sscanf