How to put numbers from txt file into vector in c++

I must say I’m completely new to C++. I got the following problem.

I’ve got a text file which only has one 8 digits number

Text-File: "01485052"

I want to read the file and put all numbers into a vector, e.g. Vector v = ( 0, 1, 4, 8, 5, 0, 5, 2 ). Then write it into another text file.

How do I implement it the best way? That’s what I made possible so far:

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

int main()
{
    char matrikelnummer[100];
 
    cout << "Enter file name: ";
    cin >> matrikelnummer;
    
    // Declare input file stream variable
    ifstream inputFile(matrikelnummer);

    string numbers;

    //Check if exists and then open the file
    if (inputFile.good()) {
        // 
        while (getline(inputFile, numbers))
        {
            cout << numbers;
        }

        // Close the file
        inputFile.close();

    }
    else // In case TXT file does not exist
    {
        cout << "Error! This file does not exist.";
        exit(0);
        return 0;
    }
    

    // Writing solutions into TXT file called Matrikelnummer_solution.txt
    ofstream myFile;
    myFile.open("Matrikelnummer_solution.txt");
    myFile << "Matrikelnummer: " << numbers << '\n';
  
    myFile.close();
    return 0;
}

>Solution :

You can use the following program for writing the number into another file and also into a vector:

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

int main()
{

    ifstream inputFile("input.txt");
    std::string numberString;
    
    int individualNumber;
    
    std::vector<int> vec;
    if(inputFile)
    {
        std::ofstream outputFile("outputFile.txt");
        while(std::getline(inputFile, numberString,'\n'))//go line by line
        {
            
            for(int i = 0; i < numberString.size(); ++i)//go character by character
            {
                individualNumber = numberString.at(i) - '0';
                outputFile << individualNumber;//write individualNumber into the output file
                vec.push_back(individualNumber);//add individualNumber into the vector
                
            }
        }
        outputFile.close();
    }
    else 
    {
        std::cout<<"input file cannot be openede"<<std::endl;
    }
    inputFile.close();
    
    //print out the vector 
    for(int elem: vec)
    {
        std::cout<<elem<<std::endl;
    }


return 0;
}

The output of the above program can be seen here.

Leave a Reply