-3

I'm pretty new in c++. I've testing a small program which takes the user input and create a file which contains the data dependent on the user input. So every time I've to change the name of file before running the code. Are there methods to use the user input as file name?

std::cout << "Enter the block size: ";
int block_size = 0;
std::cin >> block_size;

std::ofstream f;
f.open("#CAN YOU ASSIGN ME AS NAME SAME AS USER INPUT! PLEASSSEE#");

2 Answers2

2

Since you said you're creating a small program, you might want to consider taking input as command line arguments.

For example, if the user runs my program foo from the terminal, they could pass me a path by running foo /path/to/file. If your path contains spaces, the user would have to pass it between quotation marks like this foo "/path with spaces/to/file"

In order to take command line arguments this way you can do something like this:

int main(int argc, char *argv[]) {
    // argc is the amount of arguments the user passed, including the filename
    // so in our case argv[0] would return foo 
    // and argv[1] would return /path/to/file
    if (argc == 2) {
        // do stuff with argv[1] 
        // no need for std::cin
    } else {
        std::cout << "Too many or too few arguments!" << std::endl;
    }
}

Of course, this way you can only pass arguments once. If you need consistent console input from the user, the other answer is a better one.

Offtkp
  • 366
  • 2
  • 9
0

Perhaps this works?

std::cout << "Enter the block size: ";
int block_size = 0;
std::cin >> block_size;

std::cout << "Enter the file name: ";
std::ws(std::cin);
std::string filename;
std::getline(std::cin, filename);

std::ofstream f;
f.open(filename);

std::ws will eat the newline after the block size, otherwise std::getline() returns immediately:

Why does std::getline() skip input after a formatted extraction?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    This will fail if the filename has a space in it. – Vlad Feinstein Dec 13 '21 at 18:30
  • Good catch! @VladFeinstein –  Dec 13 '21 at 18:33
  • 2
    I would rewrite `std::ws(std::cin); ... std::getline(std::cin, filename);` as `std::getline(std::cin >> std::ws, filename);` Though, rather than using `std::ws` for the purpose of eating the line break left behind by `cin >> block_size`, it is typically customary to use `std::cin.ignore(std::numeric_limits::max(), '\n')` instead. – Remy Lebeau Dec 14 '21 at 01:29