C++ 从其他字符串输出文件名

C++ 从其他字符串输出文件名,c++,file,text-files,filepath,C++,File,Text Files,Filepath,嗨,这个代码有点问题 #include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; //const char* test = "connect"; #define test "connect" string con("c:\\filepath\\%s.txt", test);

嗨,这个代码有点问题

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string line;
    //const char* test = "connect";
    #define test "connect"
    string con("c:\\filepath\\%s.txt", test);
    ifstream file;
    file.open(con.c_str());
    if (file.is_open()) {
        while (file.good()) {
            getline(file, line);
            printf("setc %s\n", line.c_str());
            //cout << "setc " << line << endl;
        }
        file.close();
    } else
        cout << "Unable to open file";
    return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
弦线;
//const char*test=“connect”;
#定义测试“连接”
字符串con(“c:\\filepath\\%s.txt”,test);
ifstream文件;
open(con.c_str());
if(file.is_open()){
while(file.good()){
getline(文件,行);
printf(“setc%s\n”,第.c_str()行);

//有很多方法可以做到这一点。这里有两种:

std::string con1("c:\\filepath\\" test ".txt");
std::string con2("c:\\filepath\\" + std::string(test) + ".txt");

con1
的初始化要求
test
通过宏扩展成为字符串文本,因为它依赖于字符串文本的合并。第二种形式更为通用,
test
可以是任何可以转换为
std::string
的东西,例如
char-const*

ode>键通常位于键盘的左上角。现在您知道在哪里可以找到它,没有什么可以阻止您使用它。非常感谢您,您能告诉我您使用的是什么形式吗?例如,这种代码的样式是什么我更喜欢第二种形式,因为我不使用宏来表示常量。当然,如果您使用
std::string const test(“connect”);
直接添加常数。