I want to write the information in a .txt in c ++

0

The problem here is that it creates the file 'test.txt' but when it comes time to write to the file it does nothing ... I already saw the file permission and it's ok ... I did not understand, could anyone help me?

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
    int numero; 
    string name; 
    ofstream outFile;

    outFile.open("c:\x\test.txt");
    if (! outFile) 
    {
        cout << "erro test.txt" << endl; 
        abort(); 
    } 

    cout << "Name: \n" 
        << "Fim de arquivo (Ctrl-Z) termina a entrada de dados\n\n? "; 
    while(cin >> numero >> name){ 
        outFile << numero << " " << name<< '\n'; // << Chega aqui ele não faz nada
        cout << "? "; 
    } 
    outFile.close();
    return 0;
} 
    
asked by anonymous 18.09.2014 / 18:44

2 answers

2

The problem with your code is that the operating system is not flushing the data to the file due to CTRL + Z.

To fix this problem, just replace '\n' with endl :

outFile << numero << " " << name << endl;
    
18.09.2014 / 18:57
0
int main()
{
    std::string input;
    std::cin >> input;
    std::ofstream out("output.txt");
    out << input;
    out.close();
    return 0;
}

-------------------------------------------

std::ofstream file;
file.open("filename");
std::string my_string = "Oi qual o seu nome?\n";
file << my_string;
file.close();
    
18.09.2014 / 18:55