我正在练习将坐标存储到名为mydata的.txt文件中,然后从该文件中读取它。但是,我在阅读它时遇到了麻烦。
代码:
#include "std_lib_facilities.h"
// Classes----------------------------------------------------------------------
struct Point{
Point(int a, int b):x(a), y(b) {};
Point(){};
int x;
int y;
};
// Main-------------------------------------------------------------------------
int main()
{
vector<Point> original_points;
vector<Point> processed_points;
cout << "Please enter 7 coordinate pairs.\n";
int x, y;
while(cin >> x >> y){
if(x == -1 || y == -1) break;
original_points.push_back(Point(x, y));}
cout << "Please enter file to send points to.\n";
string name;
cin >> name;
ofstream ost(name.c_str());
if(!ost)error("can't open output file", name);
for(int i = 0; i < original_points.size(); ++i)
ost << original_points[i].x << ',' << original_points[i].y << endl;
ost.close();
cout << "Please enter file to read points from.\n";
string iname;
cin >> iname;
ifstream ist(iname.c_str());
if(!ist)error("can't write from input file", name);
while(ist >> x >> y) processed_points.push_back(Point(x, y));
for(int i = 0; i < processed_points.size(); ++i)
cout << processed_points[i].x << ',' << processed_points[i].y << endl;
keep_window_open();
}
要测试是否正在从文件中读取数据,我将其推回到已处理的点向量中,但是当我运行程序并输入点时,它不会从processed_points向量中输出任何点。我认为问题出在......
while(ist >> x >> y)
这不是从文件中读取的正确方法。任何帮助将不胜感激,谢谢。
答案 0 :(得分:3)
你在行中发出的,
ost << original_points[i].x << ',' << original_points[i].y << endl;
是你的方式,因为你不是在回读它!要么使用空格而不是逗号,要么把它读回来......
答案 1 :(得分:1)
如果您不需要强制阅读新行:
while( (ist >> x) && ist.ignore(1024,',') && (ist >> y))
processed_points.push_back(Point(x, y));
最好的方法是首先读取整行,然后使用stringstream来解析该点。
string temp;
while( std::getline(ist,temp) )
{
std::stringstream line(temp);
if( (line >> x) && line.ignore(1024,',') && ( line >> y ) )
processed_points.push_back(Point(x, y));
}
答案 2 :(得分:0)
代码(ist&gt;&gt; x&gt;&gt; y)很好,除了逗号导致istream进入y失败。字符是逗号,而不是数字,因此转换失败。亚历克斯在这里走在正确的轨道上。