Loe*_*rio 15 c++ input formatted
例如,有没有办法读取这样的格式化字符串:48754+7812=Abcs.
假设我有三个stringz X,Y和Z,我想要
X = 48754
Y = 7812
Z = Abcs
Run Code Online (Sandbox Code Playgroud)
两个数字的大小和字符串的长度可能会有所不同,所以我不想使用substring()或类似的东西.
是否有可能为C++提供这样的参数
":#####..+####..=SSS.."
Run Code Online (Sandbox Code Playgroud)
所以它直接知道发生了什么?
per*_*eal 16
#include <iostream>
#include <sstream>
int main(int argc, char **argv) {
std::string str = ":12341+414112=absca";
std::stringstream ss(str);
int v1, v2;
char col, op, eq;
std::string var;
ss >> col >> v1 >> op >> v2 >> eq >> var;
std::cout << v1 << " " << v2 << " " << var << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
hmj*_*mjd 11
一种可能性是boost::split(),它允许指定多个分隔符,并且不需要事先了解输入的大小:
#include <iostream>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
int main()
{
std::vector<std::string> tokens;
std::string s(":48754+7812=Abcs");
boost::split(tokens, s, boost::is_any_of(":+="));
// "48754" == tokens[0]
// "7812" == tokens[1]
// "Abcs" == tokens[2]
return 0;
}
Run Code Online (Sandbox Code Playgroud)
或者,使用sscanf():
#include <iostream>
#include <cstdio>
int main()
{
const char* s = ":48754+7812=Abcs";
int X, Y;
char Z[100];
if (3 == std::sscanf(s, ":%d+%d=%99s", &X, &Y, Z))
{
std::cout << "X=" << X << "\n";
std::cout << "Y=" << Y << "\n";
std::cout << "Z=" << Z << "\n";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,这里的限制是Z必须在解析输入之前确定string()的最大长度.
您可以使用scanf。它并不是过于 C++ 风格,但它只用了很少的几行代码就达到了目的:
char a[101], b[111], c[121];
sscanf(":48754+7812=Abcs", ":%100[^+]+%110[^=]=%120s", a, b, c);
string sa(a), sb(b), sc(c);
cout << sa << "-" << sb << "-" << sc << endl;
Run Code Online (Sandbox Code Playgroud)
这个想法是使用非常有限的正则表达式语法来指定您读取的字符串接受的字符。在这种情况下,第一个字符串将被读取到加号,第二个字符串将被读取到等号。
| 归档时间: |
|
| 查看次数: |
15662 次 |
| 最近记录: |