简体   繁体   中英

how to add a character variable to character array in c++

I want to write the C++ code that can help me to give the drive letter which contains the given folder. I am writing the given code and getting the error while adding the character variable to a string variable at line 11. Can anyone help me out in rectifying the below code.

#include "stdafx.h"
#include <string>
#include <windows.h>
#include <iostream>
#include "Shlwapi.h"
int main()
{
    char var;
    for (var = 'A'; var <= 'Z'; ++var)
    {
        char buffer_1[] = var +":\\PerfLogs";      ------->>>> line where i am getting the error
        char *lpStr1;
        lpStr1 = buffer_1;
        int retval;
        retval = PathFileExists(lpStr1);
        if (retval == 1)
        {
            std :: cout << "Search for the file path of : " << lpStr1;
            system("PAUSE");
        }
    }
}

You should use the string library:

std::string str1="Str 1";
std::string str2=" Str 2";
str1.append(str2);      //str1 = "Str 1 Str 2"

The specific compiler error you get is due to your attempting to add a const char* type (as a result of a string literal decayed to a pointer type) to a char . Let's not worry too much about that; rather, let's put the C++ standard library to good use:

A portable solution would be as follows:

#include <iostream>
#include <string>
// ToDo - include the header for PathFileExists
using namespace std::string_literals; // Bring in the std::string user defined literal.

int main() {
    for (auto c : "ABCDEFGHIJKLMNOPQRSTUVWXYZ"s){ // Note the user defined literal.
        std::string path = c + ":\\PerfLogs"s; // And again. This calls an overloaded `+`.
        int retval = PathFileExists(path.c_str()); // Pass the char buffer.
        if (retval == 1){
            std::cout << "Search for the file path of : " << path;
            system("PAUSE");
        }
    }
}

You can use std::string for this as others have suggested. But since it's just 1 character it wouldn't be too hard to do this:

const char buffer_1[] = { var, ':', '\\', 'P', 'e', 'r', 'f', 'L', 'o', 'g', 's', '\0' };

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