0

我正在尝试从字符串流中获取特定数据。我正在将文件中的这些数据读入字符串流。

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。

4

3 回答 3

1

如果您可以保证输入将始终采用该格式,只需将斜杠替换为空格即可。

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()<algorithm>标题中找到)

否则,您将不得不手动拆分它。

于 2013-10-16T20:50:46.180 回答
1

我建议创建一个函数来读取一个组:

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.

于 2013-10-16T20:54:01.367 回答
0

/使用将斜杠分类为空格的此类:

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) {}
};

您可以使用以下方面为输入流灌输:

iss.imbue(std::locale(iss.getloc(), new csv_whitespace));

现在斜线字符将被视为分隔符。例如:

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

输出:

2
5
6
1
11
...

于 2013-10-16T21:21:52.367 回答