How do i make C++ ask a question

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!

-Lefty
Here's an example piece of code I've put together that takes input from the user, outputs it back to them and then writes that response to a file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>
#include <string>
using namespace 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;
}


Hope this helps!
Last edited on
would i make file.txt say
~/Desktop/Test2(c++ directory)/file.txt
or would i leave it normally

also, i made a file called file.txt and it didn't save to it. So, what am i doing wrong?

It is called file.txt and i made sure it was called file.txt and not just file

i am using MacOSX yoesmite
This is the contents of the file:
2.cpp
a.out (i run this)
file.txt (txt document)
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.
Topic archived. No new replies allowed.