通过 >> 运算符将文件内容保存到变量

Saving file contents to variables through >> operator

我正在尝试读取一个文件,然后将内容(由 space 分隔)放入变量中。 文件的内容每行总是相似的。它看起来像这样:

(50,60) CIRCLE yellow 10
(100,160) CIRCLE red 20

这些值是位置、名称、颜色和直径。

这是我目前得到的:

#include <SFML/Graphics.hpp>
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "Practicum week 3");
    std::ifstream input("input.txt");
    std::string name;
    std::string line;
    sf::Vector2f position;
    sf::Color colour;

    while (std::getline(input, line))
    {
        input >> position >> name;
    }

    while (window.isOpen()) {
        sf::Event Event;
        while (window.pollEvent(Event)) {
            if (Event.type == sf::Event::Closed) { window.close(); }
        }

        // Start frame
        window.clear();

        // End frame & display contents
        window.display();
    }

    return 0;
}

这里的问题是,在 input >> position >> name; 它给我一个错误:

"Error: no operator '>>' matches these operands" operand types are: std::ifstream >> sf::vector2f

我已经看到很多针对此问题的解决方案都缺少#include,但如您所见,我已经解决了这个问题。

我是不是漏掉了什么?

字符串流怎么样?

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct vec{
    int x;
    int y;
};

int main() {
    //string s;
    //vec v;
    //stringstream ss;

    //ss << "20 10 test";
    //ss >> v.x >> v.y >> s;
    //cout << v.x << " " << v.y << " " << s.c_str(); // 20 10 test

    //@EDIT - simple parsing
    vec v;
    string s = "(2034,10)";
    size_t comaPos = s.find_first_of(',');
    string x = s.substr(1, comaPos-1);
    string y = s.substr(comaPos+1, s.find_first_of(')')-comaPos-1);

    v.x = stoi(x);
    v.y = stoi(y);

    cout << v.x << " " << v.y;

    return 0;
}

注意:您不能将“(20,10)”直接流式传输到 sf::Vector2f,但您可以像我上面那样只流式传输坐标。

The following examples will show you how to take advantage of extraction operator overloading, so that your objects can read values directly from a stream.

您需要为对象 Vector2f 重载 operator >>。这应该看起来像这样:

istream& operator>>(istream& is, const Vector2f& v2f)
{ 
    is >> v2f.data_member >> v2f.another_data_member;
    return is;
}

例如,要读取这种格式:(50,60) CIRCLE yellow 10,您的重载运算符应该类似于:*伪代码

istream& operator>>(istream& is, const Any_Object& any_obj_instantiation)
{ 
    // input variables
    int first_num, second_num;
    char open_par, close_par, comma;
    Circle circle;
    Color color;
    int last_num;
    // extract ; it skips whitespaces 
    is >> open_par >> first_num >> comma >> second_num >> cirlce >> color >> last_num;
    // failed input
    if(!is) return is;
    // wrong input format
    if(open_par != '(' || close_par != ')' || comma != ','){
        is.clear(ios_base::failbit);
        return is;
    }
    // pass the input values to the object 
    any_obj_instantiation(Vector2f(first_num, second_num), cirlce, color, last_num);

    return is;
}

以上代码片段可用作基准,并适用于您要使用输入流运算符直接填充的对象。