c++ - 从不同的字符串输出文件名

标签 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);
    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/

相关文章:

android - CMake设置目标属性使用错误的参数数量调用

Python如何在匹配后抓取一定数量的行

c++ - 有没有办法在不使用 Friend 类(C++)的情况下防止从另一个类使用公共(public)函数

c++ - 在 Windows 中使用 MIDI 流时出现问题

VBA - 在子程序中调用 Dir() 时使用 Dir() 循环

java - 使用 BufferedReader 读取 Java 中的一行

python 没有正确读取文本文件

CSV 与 TXT 文件中的 Java BufferedReader 行为

c++ - 从 'int' 到 'char *' 的无效转换

java - Spring 批处理 : Writing data to multiple files with dynamic File Name