提问人:martae 提问时间:3/24/2020 最后编辑:martae 更新时间:3/24/2020 访问量:252
IFSTREAM 不会从文件中读取值
ifstream doesn't read values from the file
问:
我正在制作一个处理点和文件的程序。我没有警告或错误,但它仍然无法正常工作。 我认为问题出在ifstream上,因为ofstream运行良好,并将输入的值放入文件中。
我得到的输出如下所示
Please enter seven (x,y) pairs:
//here the seven pairs are entered
These are your points:
//(...,...)x7 with the values
These are the points read from the file:
//and the program ends and returns 0
我希望有人能帮助我。 这是我的代码。
#include <iostream>
#include "std_lib_facilities.h"
using namespace std;
struct Point{
float x;
float y;
};
istream& operator>>(istream& is, Point& p)
{
return is >> p.x >> p.y;
}
ostream& operator<<(ostream& os, Point& p)
{
return os << '(' << p.x << ',' << p.y << ')';
}
void f() {
vector<Point> original_points;
cout << "Please enter seven (x,y) pairs: " << endl;
for (Point p; original_points.size() < 7;) {
cin >> p;
original_points.push_back(p);
}
cout << endl;
cout << "These are your points: " << endl;
for (int i=0; i < 7; i++) {
cout << original_points[i] << endl;
}
string name = "mydata.txt";
ofstream ost {name};
if (!ost) error("can't open output file", name);
for (Point p : original_points) {
ost << '(' << p.x << ',' << p.y << ')' << endl;
}
ost.close();
ifstream ist{name};
if (!ist) error("can't open input file", name);
vector<Point> processed_points;
for (Point p; ist >> p;) {
processed_points.push_back(p);
}
cout << endl;
cout << "These are the points read from the file: " << endl;
for (int i=1; i <= processed_points.size(); i++) {
cout << processed_points[i] << endl;
}
}
int main()
{
f();
return 0;
}
答:
2赞
Alan Birtles
3/24/2020
#1
输出括号和逗号,但不使用它们,因此第一次读取操作将失败。尝试:
istream& operator>>(istream& is, Point& p)
{
char open;
char close;
char comma;
is >> open >> p.x >> comma >> p.y >> close;
if (open != '(' || close != ')' || comma != ',')
{
is.setstate(std::ios_base::failbit);
}
return is;
}
由于超出了向量的边界,您的程序最后也会崩溃,您正在使用 from to 的索引,向量是 0 索引的,因此应该从 to 访问:1
length
0
length-1
for (int i = 0; i < processed_points.size(); i++) {
cout << processed_points[i] << endl;
}
或者只使用基于范围的循环:
for (auto& point : processed_points) {
cout << point << endl;
}
评论
0赞
martae
3/24/2020
谢谢!我需要这个作为输入,但我仍然有从文件中输出点的问题。我仍然得到一个空向量
0赞
john
3/24/2020
你得到一个空向量,因为你的输入失败了。
1赞
Alan Birtles
3/24/2020
@marta修复你的第二个错误会让你的代码为我工作
0赞
martae
3/24/2020
@AlanBirtles现在它也可以工作!!非常感谢您的帮助
评论
for (int i=1; i <= processed_points.size(); i++) {
这是一个 off by 1 错误吗?请记住,c++ 中的数组索引是 0 ..size-1,std::vector 也是如此for (int i=1; i <= processed_points.size(); i++) {
应该或仅使用基于 for 循环的范围。请参阅底部的示例:https://en.cppreference.com/w/cpp/language/range-forfor (int i=0; i < processed_points.size(); i++) {