我正在尝试使用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;
}
任何帮助都会很棒!谢谢!
答案 0 :(得分:3)
您有两种选择:
1)使用Objective-C ++(删除.m扩展名并将其替换为.mm)
2)转到项目设置并添加这些值:
GLIBCXX_DEBUG=1
GLIBCXXDEBUGPEDANTIC=1
在预处理器宏中。
旧Xcode: image http://img541.imageshack.us/img541/2034/screenshot20100414at101.png! 较新的Xcode:
!
示例代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, const char * argv[])
{
ofstream myfile;
myfile.open ("/Developer/afile.txt");
if(!myfile)
{
std::cout << "ERROR" std::endl;
}
myfile << "Writing this to a file.\n";
myfile.close();
return 0;
}
答案 1 :(得分:2)
如果您不想在Xcode中乱七八糟,担心您可能会破坏其他设置,请执行以下操作:
只要您构建并运行控制台程序或应用程序,请立即转到项目布局左侧的文件列表,找到“项目”目录,右键单击或按住Option键并选择“显示在Finder中“。这是Xcode每次为特定项目运行时转储构建的地方。每个工作区都有自己的构建文件夹。你应该找到你在那里选择或创建的文件,如果你想添加你自己的文件,只需拖动它然后你可以从你的控制台或应用程序调用它:myfile.open(“file.txt”);
或者只是更改项目的工作目录并使用该文件夹,这可能比/ Developer / Gibberish / Build / Debug /等更容易访问。
这样可以很容易地将代码移植到Win32或其他系统,至少对我来说是这样。
答案 2 :(得分:0)
http://kentarotanaka.com/how-to-read-input-file-for-c-in-xcode/
将文本文件移动到工作空间的项目目录中会有所帮助,如上面的链接所述。