首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在c++中的两个空格之间获取一个字符串

在c++中的两个空格之间获取一个字符串
EN

Stack Overflow用户
提问于 2017-05-09 21:42:35
回答 2查看 2K关注 0票数 1

我正在读取文本文件中的坐标。例如“050100”。我将文本文件保存在字符串向量中。我想分别得到0、50和100。我认为我可以在两个空格之间得到一个字符串,然后使用stoi将其转换为整数。但我无法实现两个空格之间的字符串分开。我分享了我尝试过的。我知道这是不对的。你能帮我找到解决办法吗?

样例文本输入:沙龙4 0 0 5 0 0 5 0 0 0 100。(4表示酒馆有4分。例:4次显示后的前两个整数(x1,y1)

代码语言:javascript
复制
    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;
        }
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-09 21:48:25

可以使用std::istringstream从文本中提取整数:

代码语言:javascript
复制
#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";
}

实例化

编辑:读取名称、数字,然后读取整数:

代码语言:javascript
复制
#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

票数 0
EN

Stack Overflow用户

发布于 2017-05-09 23:00:34

在正常情况下,从输入流(如std::ifstream )解析数字很容易,因为流已经具备了必要的解析功能。

例如,从文件输入流解析int

代码语言:javascript
复制
std::ifstream in{"my_file.txt"};
int number;
in >> number; // Read a token from the stream and parse it to 'int'.

假设您有一个包含x和y坐标的聚合类coord

代码语言:javascript
复制
struct coord {
    int x, y;
};

您可以为类coord添加自定义解析行为,以便在从输入流解析到该类时,它可以同时读取x和y值。

代码语言:javascript
复制
std::istream& operator>>(std::istream& in, coord& c) {
    return in >> c.x >> c.y; // Read two times consecutively from the stream.
}

现在,标准库中使用流的所有工具都可以解析coord对象。例如。

代码语言:javascript
复制
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坐标。

实例化

扩展活例

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43880326

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档