1

The following code reads in a text file then prints it to the screen. It works perfectly however I want to first read in the contents into an array then print out the contents and I'm not sure how to do so.

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

int main() 
{ 
string input; 

//Open file

std::ifstream inFile; 
inFile.open("Input.txt");

while (true) 
{ 

//Get input

inFile >> input;

//Avoid repetition of last line:

if(inFile.eof() ) break;

//Print input on the screen

if (input == "a")
    std::cout << "Variable: " << input << "\n";

if (input == "=")
    std::cout << "Assignment: " << input << "\n";

if (input == "3")
    std::cout << "Integer: " << input << "\n";

if (input == ";")
    std::cout << "Semicolon: " << input << "\n";

if (input == "+")
    std::cout << "Operator: " << input << "\n";

if (input == "5")
    std::cout << "Integer: " << input << "\n";

if (input == "31")
    std::cout << "Integer: " << input << "\n";

if (input == "b")
    std::cout << "Variable: " << input << "\n";

if (input == "*")
    std::cout << "Operator: " << input << "\n";

if (input == "A")
    std::cout << "Variable: " << input << "\n";

if (input == "4")
    std::cout << "Integer: " << input << "\n";

if (input == "-")
    std::cout << "Operator: " << input << "\n";

if (input == "quit")
    std::cout << "Word: " << input << "\n";
} 

//Close file

inFile.close();
return 0;
} 

End of program

1 Answer 1

1

You could store the elements in a std::vector<int> and push_back each element one by one until the end of file.Then you could loop through your vector to display all the elements.

If you prefer using simple arrays, you would have to count how many elements you have in your file, allocate that much memory to your array with new, and store the elements into your array. Don't forget to delete[] your_array in the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.