Первый импорт:
import org.apache.log4j.PropertyConfigurator;
Затем добавьте ниже код к основному методу:
String log4jConfPath ="path to/log4j.properties";
PropertyConfigurator.configure(log4jConfPath);
Создайте файл по пути и добавьте нижеприведенный код в этот файл.
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{2}: %m%n
Я сделал бы что-то вроде этого:
ifstream f("data.txt");
string str;
while (getline(f, str)) {
Point p;
sscanf(str.c_str(), "%f, %f, %f\n", &p.x, &p.y, &p.z);
points.push_back(p);
}
x, y, z должен быть плаваниями.
И включайте:
#include <iostream>
#include <fstream>
C ++ String Toolkit Library (StrTk) имеет следующее решение вашей проблемы:
#include <string>
#include <deque>
#include "strtk.hpp"
struct point { double x,y,z; }
int main()
{
std::deque<point> points;
point p;
strtk::for_each_line("data.txt",
[&points,&p](const std::string& str)
{
strtk::parse(str,",",p.x,p.y,p.z);
points.push_back(p);
});
return 0;
}
Больше примеров можно найти Здесь
Все эти хорошие примеры в стороне, в C++, который Вы обычно переопределяли бы operator >>
, чтобы Ваш тип точки достиг чего-то вроде этого:
point p;
while (file >> p)
points.push_back(p);
или даже:
copy(
istream_iterator<point>(file),
istream_iterator<point>(),
back_inserter(points)
);
соответствующая реализация оператора могла очень походить на код j_random_hacker.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm> // For replace()
using namespace std;
struct Point {
double a, b, c;
};
int main(int argc, char **argv) {
vector<Point> points;
ifstream f("data.txt");
string str;
while (getline(f, str)) {
replace(str.begin(), str.end(), ',', ' ');
istringstream iss(str);
Point p;
iss >> p.a >> p.b >> p.c;
points.push_back(p);
}
// Do something with points...
return 0;
}
Нигде рядом как краткий, и конечно я не скомпилировал это.
float atof_s( std::string & s ) { return atoi( s.c_str() ); }
{
ifstream f("data.txt")
string str;
vector<vector<float>> data;
while( getline( f, str ) ) {
vector<float> v;
boost::algorithm::split_iterator<string::iterator> e;
std::transform(
boost::algorithm::make_split_iterator( str, token_finder( is_any_of( "," ) ) ),
e, v.begin(), atof_s );
v.resize(3); // only grab the first 3
data.push_back(v);
}
Забава с повышением. Кортежи:
#include <boost/tuple/tuple_io.hpp>
#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>
int main() {
using namespace boost::tuples;
typedef boost::tuple<float,float,float> PointT;
std::ifstream f("input.txt");
f >> set_open(' ') >> set_close(' ') >> set_delimiter(',');
std::vector<PointT> v;
std::copy(std::istream_iterator<PointT>(f), std::istream_iterator<PointT>(),
std::back_inserter(v)
);
std::copy(v.begin(), v.end(),
std::ostream_iterator<PointT>(std::cout)
);
return 0;
}
Обратите внимание, что это не строго эквивалентно коду Python в Вашем вопросе, потому что кортежи не должны быть на отдельных строках. Например, это:
1,2,3 4,5,6
даст тот же вывод, чем:
1,2,3
4,5,6
Вам решать, если это - ошибка или функция :)
Этот ответ основан на предыдущем ответе j_random_hacker и использует Дух Повышения.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/spirit.hpp>
using namespace std;
using namespace boost;
using namespace boost::spirit;
struct Point {
double a, b, c;
};
int main(int argc, char **argv)
{
vector<Point> points;
ifstream f("data.txt");
string str;
Point p;
rule<> point_p =
double_p[assign_a(p.a)] >> ','
>> double_p[assign_a(p.b)] >> ','
>> double_p[assign_a(p.c)] ;
while (getline(f, str))
{
parse( str, point_p, space_p );
points.push_back(p);
}
// Do something with points...
return 0;
}
Вы могли считать файл из станд.:: iostream линию за линией, помещает каждую строку в станд.:: строка и затем использует повышение:: токенизатор для разделения его. Это не будет вполне столь же изящно/коротко как Python один, но намного легче, чем чтение вещей в символе за один раз...
Один из проектов Sony Picture Imagework с открытым исходным кодом - Pystring , который должен обеспечивать прямой перевод частей, разделяющих строки:
Pystring - это коллекция функций C ++, которые соответствуют интерфейсу и поведению методов строкового класса python с использованием std :: string. Реализованный на C ++, он не требует и не использует интерпретатор Python. Он обеспечивает удобство и знакомство с общими строковыми операциями, не включенными в стандартную библиотеку C ++