Probleme beim speichern in eine Textdatei



  • Hallo *,

    gleich nach dem Start meines Programmes, bittet das Programm um eine Eingabe. Wenn ich dann z.B. "Heute ist ein schöner Tag" eingebe, speichert er in der Textdatei nur das Wort "Heute" ab. Ich möchte aber, das er den ganzen Satz speichert. Bitte wieder mal um Euere Hilfe!!

    Gruß
    Andi

    #include <fstream.h>
    #include <iostream.h>
    #include <stdio.h>

    void main() {

    char eingabe[100];

    ofstream outfile;
    outfile.open("Test.txt");
    cout << "Bitte geben Sie einen Satz ein. ";
    cin >> eingabe;
    outfile << eingabe;
    outfile.close();

    char o[100];

    ifstream infile;
    infile.open("Test.txt");

    while (!infile.eof())
    {
    infile >> o;
    cout << o << " " << flush;
    }

    infile.close();
    getchar();

    }



  • Der >>-Operator bricht nach dem ersten whitespace(Tabulator, Leerzeichen, Zeilenrücklauf) ab. Wie wär es mit cin.getline(eingabe, sizeof(eingabe))?

    Gruß Tobias



  • #include <fstream.h>
    #include <iostream.h>
    #include <stdio.h>

    <fstream.h> und <iostream.h> sind nicht Standard.
    http://fara.cs.uni-potsdam.de/~kaufmann/?page=GenCppFaqs&faq=iostream#Answ
    Das Inkludieren von <stdio.h> ist völlig überflüssig.
    Besser:

    #include <fstream> 
    #include <iostream> 
    #include <string>
    using namespace std;
    

    void main()

    void main() ist kein gültiger Einstiegspunkt.
    http://fara.cs.uni-potsdam.de/~kaufmann/?page=GenCppFaqs&faq=main#Answ

    Besser:

    int main()
    

    char eingabe[100];

    Warum eine feste Eingabelänge, wo es in C++ doch eine feine String-Klasse gibt.
    Besser:

    string eingabe;
    

    cout << "Bitte geben Sie einen Satz ein. ";
    cin >> eingabe;
    outfile << eingabe;

    cin >> Eingabe liest nur bis zum ersten Whitespace.
    Besser:

    cout << "Bitte geben Sie einen Satz ein. "; 
    getline(cin, eingabe); 
    outfile << eingabe << endl;
    

    char o[100];

    ifstream infile;
    infile.open("Test.txt");

    Besser:

    ifstream infile("Test.txt");
    

    while (!infile.eof())
    {
    infile >> o;
    cout << o << " " << flush;
    }

    Die Bedingung ist falsch. eof() gibt erst true zurück, *nachdem* eof gelesen wurde.
    Besser:

    for (string fromFile; getline(infile, fromFile); )
    {
    cout << fromFile << " " << flush; 
    }
    


  • for (string fromFile; getline(infile, fromFile); ) 
    { 
    cout << fromFile << " " << flush;  
    }
    

    besser:

    string fromFile;
    while(getline(infile, fromFile)) {
        cout << fromFile << " " << flush; 
    }
    


  • @anle
    Ok. Mich interessiert das Warum.

    Ich halte deine Version für schlechter, da fromFile einen unnötig vergrößerten Scope hat.


Anmelden zum Antworten