c++ - 在C++中获取2个空格之间的字符串

标签 c++ string split whitespace

我正在从文本文件中读取坐标。例如“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";
}

Live Example


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

#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 << " ";
}

Live Example 2

关于c++ - 在C++中获取2个空格之间的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43880326/

相关文章:

php - 在特定子字符串之后隔离字符串末尾的子字符串

vbscript - VBS在文本文件中分割逗号分隔行

c++ - 使用 Qt/Phonon 的多 channel 音频输入

c++ - 静态初始化具有可变长度数组的结构

arrays - 当数组长度不为空时转到 “panic: runtime error: index out of range”

c++ - 将 char 指针中的字符替换为 memmove

wpf - 将 WPF PathGeometry 拆分为 "tiles"

c++ - GoogleTest 中的参数化测试未按预期工作

c++ - 将 ffmpeg 命令行转换为 C++ 编解码器设置

python - 字符串包含两个 pandas 系列