How do I make a c++ code take input from a txt file?

Sorry for my beginner question, but since the course never covered this, how do I create a c++ code that have a variable that takes input from a txt file on my computer? Say I created a int named number, how do I set it to a specific value in existing txt file? And how do I make the code automatically update the txt file if “number” were to change? Thank you

#include <iostream> #include <fstream> using namespace std; int main() { string filePath = "example.txt"; ifstream inputFile;; ofstream outputFile; (filePath); string content = ""; inputFile >> content; content += "World!"; outputFile << content; inputFile.close(); outputFile.close(); return 0; }

  1. You read input by ifstream and output by ofstream. The example and link that I given should be enough self-explanatory.

  2. If you want to add integers or something like that you have to do a type-casting with stoi.

  3. I’m pretty sure no coding language available offers automatic file updating corresponding to variable (Correct me if I’m incorrect ty) since it is extremely resource-consuming. You have to do the file I/O everytime you have updates on variable.

1 Like