【发布时间】:2013-03-22 17:23:15
【问题描述】:
我正在尝试使用 ifstream 处理一些文件。一切似乎都很好,但是当我尝试打开一个文件时它不起作用。无论我尝试输入字符串变量还是名称的字符串文字。我尝试访问的文件与项目位于同一目录中,并且确实包含内容。
项目不显示任何错误,会编译,但是每次都会说不能访问文件。
额外的头文件“simpio.h”和“console.h”只是stanford 提供的库。
#include <iostream>
#include "console.h"
#include "simpio.h"
#include <fstream>
#include <string>
using namespace std;
int countLines(ifstream & in)
{
int count = 0;
while (true) {
string line;
getline(in, line);
if (in.fail()) break;
count++;
}
return count;
}
int main()
{
ifstream in;
while (true) {
cout << "Enter name: ";
string s = getLine();
in.open(s.c_str());
if (!in.fail()) break;
cout << "Couldn't open file, try again!" << endl;
in.clear();
}
cout << "Num lines = " << countLines(in) << endl;
return 0;
}
任何帮助都会很棒!谢谢!
【问题讨论】:
-
您是否在与您要查找的文件相同的目录中启动程序?
-
你这是什么意思?该程序和所有文件都在同一个项目文件夹中。
-
ifstream肯定不能“在 Xcode 中”工作。它适用于标准库、您的程序等。类提供的功能仅取决于类,而不取决于 IDE、天气或邻居猫的当前情绪…… -
什么是
getLine()?我看到您在 countLines 方法中使用了getline(in, line)。你确定它有效吗?您应该打印出s以查看它是否正确读取。 -
这已经被问过了here