[英]Writing lines to .txt file c++
对于所有在那里的程序员! 我试图弄清楚为什么我的程序无法正常工作。 我很沮丧! 我试图编写一个程序来打开一个名为“ CSC2134.TXT”的文本文件以进行输出,然后从控制台接受文本行并将文本行写入该文件,并使用任何空字符串结束该程序。 这是我所拥有的:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
char str[80];
ofstream file1;
file1.open("CSC2134.txt");
if (file1 == 0)
{
cout << "error opening CSC2134.txt" << endl;
return 1;
}
else
{
file1 << "Enter some text:\n";
while(strlen(str) != '\n')
{
file1 << cin.getline(str,80);
if(strlen(str) == 0)
break;
}
file1.close();
}
return 0;
}
我试图弄清楚为什么我收到错误消息。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (){
ofstream myfile("CSC2134.txt");
if(myfile.is_open())
{
string str;
do{
getline(cin, str);
myfile<<str<< endl;
}while(str!="");
myfile.close();
}
else cerr<<"Unable to open file";
return 0;
}
您有一些错误:
您正在将“输入一些文本”输出到文件,而不是cout。
您的循环方式不正确,因此只有在用户输入的字符串为空时才退出应用程序。
这是一个更正的版本:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
char str[80];
fstream file1;
file1.open("CSC2134.txt");
if (!file1.is_open())
{
cout << "error opening CSC2134.txt" << endl;
return 1;
}
else
{
std::cout<< "Enter some text:\n";
cin.getline(str,80);
while((strlen(str) != 0) )
{
file1 << str;
cin.getline(str,80);
}
file1.close();
}
return 0;
}
更新:
改为运行此命令,并告诉我运行程序时的输出是什么:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
char str[80];
ofstream file1;
file1.exceptions ( ifstream::failbit | ifstream::badbit );
try {
file1.open("CSC2134.txt", fstream::in | fstream::out | fstream::binary);
}
catch (ifstream::failure e) {
cout << "Exception opening/reading file"<< e.what();
}
if (!file1.is_open())
{
cout << "error opening CSC2134.txt" << endl;
return 1;
}
else
{
std::cout<< "Enter some text:\n";
cin.getline(str,80);
while((strlen(str) != 0) )
{
file1 << str;
cin.getline(str,80);
}
file1.close();
}
return 0;
}
这是一个已纠正错误和不良做法的版本:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h> // EXIT_FAILURE
using namespace std;
int main()
{
auto const filename = "CSC2134.txt";
ofstream file1( filename );
if( file1.fail() )
{
cerr << "!Error opening " << filename << endl;
return EXIT_FAILURE;
}
string str;
cout << "Enter some text, with a blank last line:\n";
while( getline( cin, str ) && str != "" )
{
file1 << str << endl;
}
}
我个人会写and
而不是&&
,但是不能期望初学者正确配置编译器来接受它。 问题主要在于Visual C ++。 可以使用<iso646.h>
的强制包含来使其接受标准and
, or
not
接受。
提示:我使用免费的AStyle程序将缩进修复为我更清楚的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.