Hey, what is the code that makes C++ ask a question like, what country do you live in? and save the answer to a file. Or, if that is impossible, how would i make it say the answer you sent?
I'm new to c++, i know how to make it ask your name, but not a question that isn't your name. Please Help!
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main() {
string response; // a string that holds the response from the user
cout << "What country do you live in? "; // outputs the question -- can also be
// changed to a different question
getline(cin, response); // takes input from the user and places it into the string
// you can output the response they gave, like so
cout << "Your response was: " << response;
// to write the response to file, do this
ofstream file("file.txt"); // opens the file called "file.txt" for outputting
file << response; // write the response to the file
file.close(); // close the file
cin.get();
return 0;
}
In the code above the file name is a relative file path which means that the file will be written in the same directory as the running directory of your program. You could change it to the full path if you wanted but as far as I know you can't use '~' to represent the home directory, at least not in my Linux version. I'm not sure about Mac OSX because I've only ever used Linux and Windows.
If the file doesn't exist when it attempts to write it, it creates it automatically so you don't need to go about doing that yourself; and if it already exists, it overwrites it (in the default file mode).
I tested the file write code and it worked perfectly for me so if the file is not writing then an you're either looking in the wrong directory or an error occurred in opening the file. Double check that you have read and write access to the program's directory.