#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char tekst [ 99 ];
std::ofstream file;
file.open( "plik.txt" );
if( !file ) cout << "Blad otwarcia pliku do zapisu!" << endl;
else
{
while( true )
{
cin >> tekst; //:::: ( A1 )
if( !strcmp( tekst , "end" ) ) break;
file << tekst << endl; //:::: ( A2 )
}
}
file.close();
return 0;
}
/*
*( A1 )* :: Brakujący Cin
*( A2 )* :: Do porównywania tablic znaków można posłużyć się funkcją "strcmp()";
*/
Czyli "file <<" nie może działać jak cin do pliku?
Odpowiedź: może ale wymagałoby to innego podejścia i wykorzystania własnego operatora. Jako dowód podam przykład sklecony na szybko:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class CT_fileSaver
{
public:
ofstream file;
CT_fileSaver() = default;
void open( const string& fileName_A ) { file.open( fileName_A ); }
void close() { file.close(); }
operator bool() { return file.operator bool(); }
};
ostream& operator<< ( CT_fileSaver& fileSaver_A , string& text_A )
{
cin >> text_A;
if( text_A != "end" ) fileSaver_A.file << text_A;
return fileSaver_A.file;
}
int main()
{
string tekst {};
CT_fileSaver file;
file.open( "plik.txt" );
if( !file ) cout << "Blad otwarcia pliku do zapisu!" << endl;
else
{
while( tekst != "end" )
{
file << tekst << endl;
}
}
file.close();
return 0;
}
Ale to, że można, nie znaczy, że powinno się tak robić. Większość czasu w programowaniu spędza się przy debugerze więc lepiej nie utrudniać sobie sprawy nieintuicyjnym kodem.