简体   繁体   中英

How to ofstream a numeric value in a .txt file and read same data through ifstream in same program

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    string mobile;
    int N[10];
    ofstream file;
    file.open("my.txt");
    cout<<"enter mobile ";
    getline(cin, mobile);
    file<<mobile<<endl;
    cout<<"enter number ";
    cin>>N[10];
    file<<N;
    file.close();
    int a;
    cin.ignore();
    cout<<"press 1 to know details ";
    cin>>a;
    if(a==1)
    {
        ifstream file1;
        file1.open("my.txt");
        string str;
        int num;
        file1>>str;
        file1>>num;
        cout<<"company "<<str<<endl<<"number  "<<num;
        file1.close();
    }
    return 0;
}

string value is stored and read perfectly but the integer value entered is stored in the form of 0x61fdf0 and when it is supposed to again print, it always prints 0. I am trying to store a mobile number.

I am coding in code blocks.

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

const int NUM = 10;

int main()
{
    string mobile;
    int n[NUM];
    ofstream file;
    file.open("my.txt");
    cout << "enter mobile: ";
    getline(cin, mobile);
    file << mobile << endl;
    cout << "enter number ";
    file << n[0];
    file.close();
    int a;
    cin.ignore();
    cout << "press 1 to know details ";
    cin >> a;
    if(a==1)
    {
        ifstream file1;
        file1.open("my.txt");
        string str;
        int num;
        (file1, str);
        file1 >> num;
        cout << "company: " << str <<"\nnumber: " << num << endl;
        file1.close();
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM