代码转换(c#到c+;+;)
第一部分:代码转换(c#到c+;+;),c#,c++,C#,C++,第一部分: public static void ReadPoints(string aFile, Point2D [] pArray) { try { using(StreamReader sr = new StreamReader(aFile)) { sr.BaseStream.Seek(0,SeekOrigin.Begin); fo
public static void ReadPoints(string aFile, Point2D [] pArray)
{
try
{
using(StreamReader sr = new StreamReader(aFile))
{
sr.BaseStream.Seek(0,SeekOrigin.Begin);
for(int i=0;i<pArray.Length;i++)
{
string line = sr.ReadLine();
int index = line.IndexOf("\t");
pArray[i].X = double.Parse(line.Substring(0,index));
pArray[i].Y = double.Parse(line.Substring(index+1,line.Length-(index+1)));
}
}
}
catch(Exception e)
{
Console.WriteLine("Warning: An exception has been thrown at ReadPoints()!");
Console.WriteLine(e.ToString());
return;
}
return;
}
}
下面的代码是Point2D类的定义。上面的代码用于读取点的坐标并从字符串中读取int
class Point2D
{
public:
double get_x();
void set_x(double value);
double get_y();
void set_y(double value);
private:
double x;
double y;
};
double Point2D::get_x()
{
return x;
}
void Point2D::set_x(double value)
{
x = value;
}
double Point2D::get_y()
{
return y;
}
void Point2D::set_y(double value)
{
y = value;
}
对于你的第一部分,合理的习惯用法C++看起来是这样的:
struct Point2D {
double x, y; // pass-through get/set pair gained nothing over public data.
friend std::istream &operator>>(std::istream &is, Point2D &p) {
return is >> p.x >> p.y;
}
};
std::ifstream infile(aFile);
std::vector<Point2D> points{std::istream_iterator<Point2D>(infile),
std::istream_iterator<Point2D>()};
bool is_int(std::string const &in) {
// technically `-` isn't a digit, but we want to allow it.
static const std::string digits{ "-0123456789" };
return in.find_first_not_of(digits) == std::string::npos;
}
int readint(std::string const &prompt) {
std::string input;
do {
std::cout << prompt;
std::getline(std::cin, input);
} while (!is_int(input) && std::cout << "Bad input (non-digit entered)\n");
return stoi(input);
}
是的,这有公共数据——这通常不是一个好主意。然而,在本例中,这可能不是一个糟糕的想法——实际上,这是您的代码使用私有数据和纯粹的传递get/set对所完成的工作。如果类确实可以/应该强制执行一些不变量,我完全支持将数据私有化并强制执行它们,但是如果不强制执行不变量,则将数据私有化并添加get/set对只会增加语法噪音,而不是实用性。要使用它从文件中读取一些数据,可以执行以下操作:
struct Point2D {
double x, y; // pass-through get/set pair gained nothing over public data.
friend std::istream &operator>>(std::istream &is, Point2D &p) {
return is >> p.x >> p.y;
}
};
std::ifstream infile(aFile);
std::vector<Point2D> points{std::istream_iterator<Point2D>(infile),
std::istream_iterator<Point2D>()};
bool is_int(std::string const &in) {
// technically `-` isn't a digit, but we want to allow it.
static const std::string digits{ "-0123456789" };
return in.find_first_not_of(digits) == std::string::npos;
}
int readint(std::string const &prompt) {
std::string input;
do {
std::cout << prompt;
std::getline(std::cin, input);
} while (!is_int(input) && std::cout << "Bad input (non-digit entered)\n");
return stoi(input);
}
目前,这并不强制要求-
位于数字的开头,因此它允许像3-2
这样的输入。如果您需要确保不发生此类情况(可能是数字在范围内),您需要重写一点is_int
,以严格执行您想要的内容