我正在读取文本文件中的坐标。例如“050100”。我将文本文件保存在字符串向量中。我想分别得到0、50和100。我认为我可以在两个空格之间得到一个字符串,然后使用stoi将其转换为整数。但我无法实现两个空格之间的字符串分开。我分享了我尝试过的。我知道这是不对的。你能帮我找到解决办法吗?
样例文本输入:沙龙4 0 0 5 0 0 5 0 0 0 100。(4表示酒馆有4分。例:4次显示后的前两个整数(x1,y1)
for (int j = 2; j < n * 2 + 2; j++){
size_t pos = apartmentInfo[i].find(" ");
a = stoi(apartmentInfo[i].substr(pos + j+1,2));
cout << "PLS" << a<<endl;
}发布于 2017-05-09 21:48:25
可以使用std::istringstream从文本中提取整数:
#include <sstream>
#include <vector>
#include <string>
#include <iostream>
int main()
{
std::string test = "0 50 100";
std::istringstream iss(test);
// read in values into our vector
std::vector<int> values;
int oneValue;
while (iss >> oneValue )
values.push_back(oneValue);
// output results
for(auto& v : values)
std::cout << v << "\n";
}实例化
编辑:读取名称、数字,然后读取整数:
#include <sstream>
#include <vector>
#include <string>
#include <iostream>
int main()
{
std::string test = "Saloon 4 0 0 50 0 50 100 0 100";
std::string name;
int num;
std::istringstream iss(test);
iss >> name;
iss >> num;
std::cout << "Name is " << name << ". Value is " << num << "\n";
std::vector<int> values;
int oneValue;
while (iss >> oneValue )
values.push_back(oneValue);
std::cout << "The values in vector are:\n";
for(auto& v : values)
std::cout << v << " ";
}活生生的例子2
发布于 2017-05-09 23:00:34
在正常情况下,从输入流(如std::ifstream )解析数字很容易,因为流已经具备了必要的解析功能。
例如,从文件输入流解析int:
std::ifstream in{"my_file.txt"};
int number;
in >> number; // Read a token from the stream and parse it to 'int'.假设您有一个包含x和y坐标的聚合类coord。
struct coord {
int x, y;
};您可以为类coord添加自定义解析行为,以便在从输入流解析到该类时,它可以同时读取x和y值。
std::istream& operator>>(std::istream& in, coord& c) {
return in >> c.x >> c.y; // Read two times consecutively from the stream.
}现在,标准库中使用流的所有工具都可以解析coord对象。例如。
std::string type;
int nbr_coords;
std::vector<coord> coords;
if (in >> type >> nbr_coords) {
std::copy_n(std::istream_iterator<coord>{in}, nbr_coords, std::back_inserter(coords));
}这将读取正确数量的coord对象并将其解析为一个向量,每个coord对象都包含一个x和y坐标。
实例化
扩展活例
https://stackoverflow.com/questions/43880326
复制相似问题