【发布时间】:2021-03-30 11:37:14
【问题描述】:
我正在尝试将一系列坐标写入数组以便执行计算,但我无法正确读取文件,因为我无法忽略标题,当我删除时标头似乎也没有正确地将值写入数组。
坐标文件为txt如下。
Coordinates of 4 points
x y z
-0.06325 0.0359793 0.0420873
-0.06275 0.0360343 0.0425949
-0.0645 0.0365101 0.0404362
-0.064 0.0366195 0.0414512
非常感谢任何有关代码的帮助。我尝试使用 .ignore 跳过两个标题行,但它们似乎没有按预期工作。
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
int main() {
int i = 1;
int count = 1;
char separator;
const int MAX = 10000;
int x[MAX];
int y[MAX];
int z[MAX];
int dist[MAX];
char in_file[16]; // File name string of 16 characters long
char out_file[16];
ifstream in_stream;
ofstream out_stream;
out_stream << setiosflags(ios::left); // Use IO Manipulators to set output to align left
cout << "This program reads a series of values from a given file, saves them into an array and performs calculations." << endl << endl;
// User data input
cout << "Enter the input in_file name: \n";
cin >> in_file;
cout << endl;
in_stream.open(in_file, ios::_Nocreate);
cout << "Enter the output file name: \n";
cin >> out_file;
cout << endl;
out_stream.open(out_file);
// While loop in case in_file does not exist / cannot be opened
while (in_stream.fail()) {
cout << "Error opening '" << in_file << "'\n";
cout << "Enter the input in_file name: ";
cin >> in_file;
in_stream.clear();
in_stream.open(in_file, ios::_Nocreate);
}
while (in_stream.good) {
in_stream.ignore(256, '\n');
in_stream.ignore(256, '\n');
in_stream >> x[i] >> separator >>y[i] >> separator >> z[i];
i++;
count = count + 1;
}
cout << x[1] << y[1] << z[1];
in_stream.close();
out_stream.close();
return 0;
}
【问题讨论】:
-
除了c++ - Why is iostream::eof inside a loop condition (i.e.
while (!stream.eof())) considered wrong? - Stack Overflow中描述的问题之外,while (in_stream.good)是不好的,因为该函数直接用作条件而不是被调用。 -
您似乎忽略了每 3 行中的 2 行,因为您在循环中
ignore而不是只跳过前两行一次 -
@MikeCAT 读取文件的正确条件应该是什么?
-
在循环之前忽略或读取前两行 getline 并使你的循环
while (in_stream >> x[i] >> y[i] >> z[i]) { ... }您可以考虑使用std::vector而不是制作一个巨大的数组,浪费或耗尽空间. -
std::getline用于阅读,而非写作。