C++ 写入文件
我想写入一个名为TEXT的文件,并在每次运行程序时附加到该文件中。它可以编译,但不接受输入。请帮忙;我是编程新手 以下是我正在使用的代码:C++ 写入文件,c++,C++,我想写入一个名为TEXT的文件,并在每次运行程序时附加到该文件中。它可以编译,但不接受输入。请帮忙;我是编程新手 以下是我正在使用的代码: #include <iostream> #include <fstream> #include <string> using namespace std; main () { string line; ifstream file; file.open("TEXT",ios::in |ios::ap
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
main ()
{
string line;
ifstream file;
file.open("TEXT",ios::in |ios::app);
if (file.is_open())
{
while (file.good() )
{
getline (file,line);
cout << line << endl;
}
file.close();
} else
cout << "Unable to open file";
}
此程序成功打开文本进行阅读,并将其内容打印到标准输出 如果要从输入中读取,则需要从标准输入中读取行: 而不是
getline (file,line);
cout << line << endl;
然后,您将需要使用ios::out标志而不是ios::in打开文件进行写入,并且不使用ios::app并在其中写入,而不是在stdout中写入:
而不是
getline (file,line);
cout << line << endl;
我不确定您想做什么,但这里有一些文本文件的基本输入/输出操作。希望能有帮助
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
ifstream input("TEXT", ios::in); // Opens "TEXT" for reading
if(input.fail())
{
cout << "Input error: could not open " << "TEXT" << endl;
exit(-1);
}
while(getline(input, line))
{
cout << line << endl; // prints contents of "TEXT"
}
input.close(); // close the file
ofstream output("TEXT", ios::app); // opens "TEXT" for writing
if(output.fail())
{
cout << "Output error: could not open " << "TEXT" << endl;
exit(-1);
}
output << "I am adding this line to TEXT" << endl; // write a line to text
output.close(); // close the file
return 0;
}
要写入文件而不是从中读取,您基本上需要将文件类型更改为流的输出流、file-To-cin和cout-To-file。你也可以简化一些事情。如果下一个操作成功,流将自动转换为真值,如果失败,流将自动转换为假值,因此您可以通过引用流来测试流。while file没有什么问题。很好,它不像while file那样惯用 参考资料:
如果你想写入文件,那么为什么你要打开它进行输入并从中读取?这段代码离你想要的太远了,你最好从头开始。你能在代码中进行更改吗…当我运行这段代码时,它不接受输入。。。
#include <iostream>
#include <fstream>
#include <string>
#include <cerrno>
using namespace std;
int main () {
string line;
string fname="TEXT";
/* You can open a file when you declare an ofstream. The path
must be specified as a char* and not a string.[1]
*/
ofstream fout(fname.c_str(), ios::app);
// equivalent to "if (!fout.fail())"
if (fout) {
while (cin) {
getline(cin,line);
fout << line << endl;
}
fout.close();
} else {
/* Note: errno won't necessarily hold the file open failure cause
under some compilers [2], but there isn't a more standard way
of getting the reason for failure.
*/
cout << "Unable to open file \"" << fname << "\": " << strerror(errno);
}
}