C++ 如何格式化stringstream的输出?
我试图从stringstream中获取特定数据。 我正在将此数据从文件读入stringstreamC++ 如何格式化stringstream的输出?,c++,file,format,string-formatting,stringstream,C++,File,Format,String Formatting,Stringstream,我试图从stringstream中获取特定数据。 我正在将此数据从文件读入stringstream f 2/5/6 1/11/6 5/12/6 8/10/6 现在,当我想把数据读入变量时,我该怎么做? 这是我想要的格式 stringstream s(line); string tmpn; int t[4]; int a, b, c, d, e; s >>tmpn >>a >>t[0] >>b >>c >>t[1] >
f 2/5/6 1/11/6 5/12/6 8/10/6
现在,当我想把数据读入变量时,我该怎么做?
这是我想要的格式
stringstream s(line);
string tmpn;
int t[4];
int a, b, c, d, e;
s >>tmpn >>a >>t[0] >>b >>c >>t[1] >>b >>d >>t[2] >>b >>e >>t[3] >>b;
所以基本上我想要第一个字符,然后每个数字在没有斜线的单独值中
我该怎么做?
我试过使用sscanf,但那太可怕了!
我使用的是C++/CLI。如果您能保证输入始终采用该格式,只需将斜杠替换为空格即可
replace(line.begin(), line.end(), '/', ' ');
stringstream s(line);
string tmpn;
int t[4];
int a, b, c, d, e;
s >>tmpn >>a >>t[0] >>b >>c >>t[1] >>b >>d >>t[2] >>b >>e >>t[3] >>b;
(replace()
位于
标题中)
否则,您必须手动拆分它。我建议创建一个函数来读取组:
void read_group(std::stringstream& s, int& a, int& b, int &c)
{
char temp;
s >> a;
s >> temp; // First '/'
s >> b;
s >> temp; // second '/'
s >> c;
}
如果组和组中的数字是相关的,您可能希望为它们创建一个类,该类使用将斜杠分类为空白的方法从
stringstream
:
struct csv_whitespace
: std::ctype<char>
{
static const mask* make_table()
{
static std::vector<mask> v(classic_table(), classic_table() + table_size);
v['/'] |= space;
return &v[0];
}
csv_whitespace(std::size_t refs = 0) : ctype(make_table(), false, refs) {}
};
现在斜杠字符将被视为分隔符。例如:
std::istringstream iss("2/5/6 1/11/6 5/12/6 8/10/6");
iss.imbue(std::locale(iss.getloc(), new csv_whitespace));
int i;
while (iss >> i)
{
std::cout << i;
}
std::istringstream iss(“2/5/6 1/11/6 5/12/6 8/10/6”);
imbue(std::locale(iss.getloc(),新的csv_空格));
int i;
while(iss>>i)
{
太感谢了。我不知道为什么我没有想到这个!哈哈哈
std::istringstream iss("2/5/6 1/11/6 5/12/6 8/10/6");
iss.imbue(std::locale(iss.getloc(), new csv_whitespace));
int i;
while (iss >> i)
{
std::cout << i;
}