我在Xcode中遇到此代码时出现问题:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream out;
char c;
out.open("call_data.txt");
if (out.fail())
cout << "failed." << endl; exit(1);
cout << "Print something to a file :" << exit(1);//I get the error here
cin >> c;
out << c;
out.close();
return 0;
}
有人能告诉我为什么会收到这个错误吗?我无法弄清楚。我可能错误地打开输出流吗?我觉得它之前就像这样。
答案 0 :(得分:1)
使用合理的格式化代码如下所示:
ofstream out;
char c;
out.open("call_data.txt");
if (out.fail())
cout << "failed." << endl;
exit(1);
cout << "Print something to a file :" << endl; //exit(1) shouldn't be here either
cin >> c;
out << c;
out.close();
始终会发生对exit
的调用,以后无法访问任何内容。使用{}
表示多语句if
:
if (out.fail()) {
cout << "failed." << endl;
exit(1);
}
答案 1 :(得分:0)
您的错误可能是因为您忘记在if语句中使用括号。这是它应该是什么样子:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream out;
char c;
out.open("call_data.txt");
if (out.fail())
{
cout << "failed." << endl;
exit(1);
}
cout << "Print something to a file :" << exit(1);//I get the error here
cin >> c;
out << c;
out.close();
return 0;
}