您好,我在使用这段代码时遇到了一些麻烦
#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;
}
谁能告诉我哪里出了问题
这就是我想要的
'con' 是为了从 'test' 获取它的文件名
如果你能帮助我,我将不胜感激:)
最佳答案
有很多方法可以做到这一点。这里有两个:
std::string con1("c:\\filepath\\" test ".txt");
std::string con2("c:\\filepath\\" + std::string(test) + ".txt");
con1
的初始化需要test
通过宏展开成为字符串文字,因为它依赖于字符串文字的合并。第二种形式更通用,test
可以是任何可以转换为 std::string
的东西,例如 char const*
。
关于c++ - 从不同的字符串输出文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14009871/