How to take input from file in C++?

Hi Everyone,
I wanted to take the input from a .txt file and use it in my c++ code. The main issue is that there are very long input in the form mentioned below:

forward 2
down 1
down 7
forward 6
down 6
down 6

But the line numbers are not fixed, i.e. the number of input in the file will keep on changing as it is dynamically generated each time by the online judge.

Could someone please suggest how to take input from a dynamically changing file.

Thanks

// Create a text string, which is used to output the text file
string myText;

// Read from the text file
ifstream MyReadFile("a.txt");

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) {
     // Output the text from the file
    cout << myText;
}

// Close the file
MyReadFile.close();

1 Like

You might want to elaborate on what you’re trying to achieve. Share information about the OS you’re using too.

1 Like

I am just trying to get the input and run it with my program to get a output and want to submit the result.
OS information : Windows
Thanks

But how to store the string and the number into some variable? with this process I will be able to output the content of the file in the console.
I want to store the string and into pair into variable so as to process it into result.
Thanks

What’s that program?

 // Create a text string, which is used to output the text file
    string myText;
    
    // Read from the text file
    ifstream MyReadFile("a.txt");
    
    
    vector<int> integers;
    vector<string> str;
    
    // Use a while loop together with the getline() function to read the file line by line
    while (getline (MyReadFile, myText)) {
         // Output the text from the file
        string a="";
        int i;
        for(i=0;myText[i]!=' ';i++){
            a+=myText[i];
        }
    
        str.push_back(a);
        a="";
        for(;i<myText.length();i++){
            a+=myText[i];
        }
        integers.push_back(stoi(a));
    
    }
    
    // Close the file
    MyReadFile.close();

1 Like

Thanks a lot for sharing!