我正在从文本文件中读取坐标。例如“0 50 100”。我将我的文本文件保存在一个字符串 vector 中。我想分别得到 0 和 50 和 100。我认为我可以将其作为获取 2 个空格之间的字符串,然后使用 stoi 将其转换为整数。但是我无法分别在两个空格之间获取一个字符串。我分享了我的尝试。我知道这是不正确的。你能帮我找到我的解决方案吗?
示例文本输入:Saloon 4 0 0 50 0 50 100 0 100。(4 表示 saloon 有 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;
}
最佳答案
您可以使用 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 << " ";
}
关于c++ - 在C++中获取2个空格之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43880326/