简体   繁体   中英

How to append a variable in to the output file's name in C++

I have a C++ project which output data in to a file. The following is the code for it.

case 3:
            {
                outfile.open("price-change.csv");
                if(! outfile)
                {
                    cout << "Can not open outfile" << endl;
                    exit(1);
                }

i want to mutate the file name as price-change-2014-12-23 where 2014-12-23 is a variable added to the file name, price change. Any idea guys? Thanks in advance.

std::string filename = "price-change-" + datestring + ".csv"
outfile.open(filename);

Should do it.

Thomas Matthews points out in the comments that older compilers and compilers without C++11 support enabled the file must be opened with a const char * rather than a std::string . If the above produces an error message and C++11 cannot be used, open the file with

outfile.open(filename.c_str());

而且,如果您涉及整数或浮点数之类的数字,则可以使用stringstream轻松构建日期字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM