【发布时间】:2012-07-31 01:17:58
【问题描述】:
我有一个包含很多数字的文件。该文件基本上看起来像“192 158 100 0 20 200”。如何一次加载文件编号 1 并在 C++ 中将它们显示在屏幕上?
【问题讨论】:
-
要获得漂亮、精美的单行字(至少对于阅读和打印部分),请查看
std::copy、std::istream_iterator和std::ostream_iterator。
我有一个包含很多数字的文件。该文件基本上看起来像“192 158 100 0 20 200”。如何一次加载文件编号 1 并在 C++ 中将它们显示在屏幕上?
【问题讨论】:
std::copy、std::istream_iterator 和std::ostream_iterator。
试试这样的:
int val;
std::ifstream file("file");
while (file >> val)
std::cout << val;
【讨论】:
while(EOF TEST),因为仅在您读取文件末尾并且最后一次成功读取读取到(但不超过 EOF)之后才设置 EOF 标志。循环应该是while(file >> val) 这样如果读取成功,循环就进入了。
下面的程序应该打印每个数字,每行一个:
#include <iostream>
#include <fstream>
int main (int argc, char *argv[]) {
std::ifstream ifs(argv[1]);
int number;
while (ifs >> number) {
std::cout << number << std::endl;
}
}
【讨论】:
ifs >> number 可能会失败。标准模式是while(ifs >> number),因此如果失败,则不会进入循环。目前,您将两次打印文件中的最后一个值。
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
int main() {
std::ifstream fs("yourfile.txt");
if (!fs.is_open()) {
return -1;
}
// collect values
// std::vector<int> values;
// while (!fs.eof()) {
// int v;
// fs >> v;
// values.push_back(v);
// }
int v;
std::vector<int> values;
while (fs >> v) {
values.push_back(v);
}
fs.close();
// print it
std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
【讨论】:
while(EOF Test) 这几乎总是错误的。问题是在您阅读 EOF 之前,EOF 不是真的。因此,最后一个数字将读取到(但不会超过 EOF)。然后循环内的读取将失败,您将随机值推送到values。你应该做的是while(fs >> v)。并非所有语言都适用这种模式,而不仅仅是 C++。
请考虑以下代码:
ifstream myReadFile;
myReadFile.open("text.txt");
int output;
if (myReadFile.is_open())
{
while (fs >> output) {
cout<<output;
}
}
//Of course closing the file at the end.
myReadFile.close();
同样,在使用上述示例时,请在代码中包含 iostream 和 fstream。
请注意,您需要开始打开一个文件流进行读取,您可以尝试逐个字符地读取它,并检测它之间是否有任何空白。
祝你好运。
【讨论】:
另一种方法:
std::string filename = "yourfilename";
//If I remember well, in C++11 you don't need the
//conversion to C-style (char[]) string.
std::ifstream ifs( filename.c_str() );
//Can be replaced by ifs.good(). See below.
if( ifs ) {
int value;
//Read first before the loop so the value isn't processed
//without being initialized if the file is empty.
ifs >> value;
//Can be replaced by while( ifs) but it's not obvious to everyone
//that an std::istream is implicitly cast to a boolean.
while( ifs.good() ) {
std::cout << value << std::endl;
ifs >> value;
}
ifs.close();
} else {
//The file couldn't be opened.
}
错误处理可以通过多种方式完成。
【讨论】:
while(ifs >> value)。这也使代码更加简洁。您正在使用 if (ifs) 但 while(ifs.good()) 需要在使用上保持一致。就我个人而言,我什至不会测试(除非您报告错误)。无需显式关闭 RAII 将正确关闭它codereview.stackexchange.com/q/540/507