我正在尝试读取一个文件,然后将内容(以空格分隔)放入变量中。 文件的内容每行总是相似的。它看起来像这样:
(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,但如您所见,我已经解决了这个问题。
我错过了什么吗?
最佳答案
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
,您的重载运算符应该如下所示:*slightly in pseudo-code
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;
}
上面的代码片段可以用作基准并适用于您想要直接使用输入流运算符填充的对象。
关于c++ - 通过 >> 运算符将文件内容保存到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32657804/