【发布时间】:2019-04-11 08:34:44
【问题描述】:
我正在一个 SVG 文件中绘制形状,该文件是通过使用 .dat 文件提供的输入生成的。
我需要从 .dat 文件中取出一行,从中删除 4 个单独的整数,并将这些整数保存到一个向量中。为此,我尝试创建一个类 square,它包含 4 个整数(它们代表正方形的左上角和右下角坐标)。最好,我可以在类的构造函数中执行此操作,但我不知道该怎么做。
基本上,我知道我会有一个看起来像“1 1 50 50”的字符串,我想把它变成 4 个整数。我遇到的问题是我需要将其设为类对象的 4 个整数,而不仅仅是 4 个整数。
class SQ
{
public:
sq() = default;
static int tl_x;
static int tl_y; //top left corner
static int br_x;
static int br_y; //bottom right corner
};
我已经尝试了下面的代码,但它显然不起作用,因为它只保存遇到的第一个整数。
while (getline(file,s))
{
int *f = new int(stoi(s));
vec.push_back(f);
}
感谢您的帮助:)
【问题讨论】:
-
当字符串不为空时重复?
-
欢迎来到 SO。我相信之前有人问过这个问题:How do I convert an inputted string of numbers into an int array?
-
在你的循环中,
int f; std::stringstream ss (s); while ((ss >> f)) vec.push_back(f);(注意:不是int *f) -
您可以使用
strtok将字符串拆分为四个字符串,然后在每个子字符串上调用stoi