C++ -- 如何将一个字符串转换为多个整数
C++ -- How to convert a string into multiple integers?
我正在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);
}
我感谢任何帮助:)
使用 stringstream
、 istream_iterator
、 back_inserter
和 copy
算法,我们可以这样写:
while (getline(file, s))
{
auto str_stream = stringstream(s);
auto str_iter = istream_iterator< int >(str_stream);
const auto end_of_str = istream_iterator< int >();
auto back_insert_iter = back_inserter(vec);
copy(str_iter, end_of_str, back_insert_iter);
}
如果您将一行整数(如 "1 1 50 50"
(读取到字符串中,并且需要从字符串中解析整数,那么处理转换的标准C++方法是从字符串创建stringstream
并使用 iostream 从字符串中提取整数。
例如:
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
int main (void) {
std::istringstream is { "1 1 50 50n" }; /* simulated input */
std::string s;
std::vector<int> vect;
while (getline (is, s)) { /* read string */
int f; /* declare int */
std::stringstream ss (s); /* make stringstream from s */
while ((ss >> f)) /* read ints from ss into f */
vect.push_back (f); /* add f to vector */
}
for (auto& i : vect) /* output integers in vector */
std::cout << i << 'n';
}
(如果需要单独存储所有行,只需使用std::vector<std::vector<int>> vect;
(
请注意,初始istringstream
只是模拟getline
输入的一种方式。
示例使用/输出
$ ./bin/ssint
1
1
50
50
仔细查看,如果您有其他问题,请告诉我。
您不必将行读入std::string
,因为您可以逐个读取整数并直接将它们存储到向量中。尝试类似下面的操作。
#include <fstream>
#include <vector>
int main()
{
std::ifstream ifile("./yourfile.dat");
std::vector<int> theIntegers;
for (int idx = 0, val = 0; idx < 4; ++idx)
{
ifile >> val;
theIntegers.push_back(val);
}
}
编辑:只需通过引用构造函数传递std::istream
即可读取构造函数中的文件。在下面的示例中,我假设您希望准确读取四个整数,同时丢弃该行的可能其余部分。
#include <istream>
#include <string>
#include <array>
/*
* This class holds four integers to describe a square
* On construction, it reads four integers from a given std::istream
* Note that it does not check the formatting of the input file and
* that it reads the first four integers and discards the remaining
* characters until the next newline character.
*/
class Square
{
std::array<int, 4> d_coordinates;
public:
Square() = delete;
Square(std::istream &iFile)
{
for (int idx = 0, val = 0, n = size(d_coordinates); idx < n; ++idx)
{
iFile >> val;
d_coordinates[idx] = val;
}
// Remove the newline character at the end of this line
// If you for some reason want to store multiple squares
// on a single line, then just remove the next two lines
std::string tmp;
std::getline(iFile, tmp);
}
};
int main()
{
std::ifstream ifile("./yourFile.dat");
Square x(ifile);
Square y(ifile);
Square z(ifile);
}