我有一项使用 C++ 的工作要做,它应该读取一个文件 .txt 并使用其中的信息。但是我们的老师给了我们开头的代码来帮助我,我真的不明白。我是 C++ 的初学者,所以我已经找了好几个小时了,但我没有找到答案,谢谢!
这是一段代码:
int main(int argc, const char** argv)
{
std::ifstream* myfile = NULL;
if (argc == 2) {
file = myfile = new std::ifstream(argv[1]);
if (myfile->fail())
std::cerr << "Error at the opening of the file'" << argv[1] << "'" << std::endl;
}
else
std::cerr << "No file name." << std::endl;
while (*file) {
std::string event;
*file >> event;
if (!(*file)) break;
if (event == "recipe") {
std::string namerecipe;
*file >> recipe;
...
所以我不明白?什么是 * 文件?和文件?它是文件上的指针吗?为什么没有像 get line 这样的功能在上面工作?为什么“while *file”应该这样做? 非常感谢 !
最佳答案
int main(int argc, const char** argv)
{
一个典型的函数入口点。
std::ifstream* myfile = NULL;
if (argc == 2) {
确保有足够的参数从 argv[1]
获取文件名。
file = myfile = new std::ifstream(argv[1]);
动态分配文件输入流并尝试使用它打开 argv[1]
中指定的文件。然后将该文件流分配给两个指针,file
和 myfile
。我承认没有看到有两个指针的意义,但我也没有首先看到指针的意义。
if (myfile->fail())
调用流的fail
函数。这将测试流是否有任何问题。此时所有要测试的是流是否打开。
std::cerr << "Error at the opening of the file'" << argv[1] << "'" << std::endl;
}
else
std::cerr << "No file name." << std::endl;
while (*file) {
取消引用 file
指针以对文件对象进行操作。这将具有调用流的 bool 运算符的效果。这与调用 !file->fail()
具有相同的(C++11 或更新的)或如此相似,以至于在这种情况下(C++11 之前)效果无关紧要。更多关于 operator bool 的信息:http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool
std::string event;
*file >> event;
从流中读取一个以空格分隔的标记,一个单词。
if (!(*file)) break;
运算符再次 bool 。失败时退出循环。
if (event == "recipe") {
std::string namerecipe;
*file >> recipe;
从流中读取另一个词。
代码可以按照这些行重写:
int main(int argc, const char** argv)
{
if (argc == 2)
{
std::ifstream myfile(argv[1]);
if (myfile)
{
std::string event;
while (myfile >> event)
{
//this function is getting deep. Consider spinning this off into a new function
if (event == "recipe")
{
std::string namerecipe;
if (myfile >> recipe)
{
// do stuff that is missing from code sample
}
else
{
// handle error
}
}
}
}
else
{
std::cerr << "Error at the opening of the file'" << argv[1] << "'" << std::endl;
}
}
else
{
std::cerr << "No file name." << std::endl;
}
}
关于c++ - 看不懂这段代码?这是关于在 C++ 中读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36464974/