简体   繁体   中英

Converting char to std::string, then concatenating

Although I have seen many similar questions, I couldn't find a solution to this particular problematic.

My problem is very simple, yet I'm totally stuck. I have a simple c++ function, for which I tried something like

void function1(char* filapp) {
   std::string filapp_2 = "";
   fprintf(stdout, "filapp_2: %s\n", filapp_2.c_str());
   filapp_2  += "A";
   fprintf(stdout, "filapp_2: %s\n", filapp_2.c_str());
   filapp_2  += "B";
   fprintf(stdout, "filapp_2: %s\n", filapp_2.c_str());
   filapp_2  += std::string(filapp);
   fprintf(stdout, "filapp_2: %s\n", filapp_2.c_str());
   filapp_2  += "D";
   fprintf(stdout, "filapp_2: %s\n", filapp_2.c_str());
}

If the input value is "C", then this code prints

filapp_2:
filapp_2: A
filapp_2: AB
filapp_2: ABC
filapp_2: ABC

I tried many other methods, still this is basically always the result. I tried prepending and it erases "AB". I don't know why that is.

It seems like when filapp is concatenate, the string is no longer dynamic and becomes constant. Maybe it related to the fact that this function is called through a fortran interface, which constrains the memory? The interface looks like

module module_name
    implicit none
    interface
        subroutine function1 (filapp) bind(c)
            use iso_c_binding
            character(kind=c_char) :: filapp(*)
        end subroutine function1
    end interface
end module

EDIT: I was asked to add the fortran part which calls the function. So I'm working on a huge, so everything is really intricate. Basically, the fortran function looks like

call function1(filapp)

where filapp is defined as

character(len=fnlen) :: filapp

which is different then in the interface it-self. I'm not sure what this implies.

The std::string constructor std::string(filapp) requires filapp to be null-terminated. The actual argument in the Fortran reference to the subroutine will not be null-terminated unless you make an effort for it be be such.

Consider the example

use, intrinsic :: iso_c_binding, only : c_char, c_null_char
use module_name

call function1(c_char_'C'//c_null_char)
end

and look at what happens without the appended c_null_char .

More generally, a variable declared like

character(len=fnlen, kind=c_char) :: filapp

as a scalar character of length fnlen may be passed as an argument to the assumed-size dummy argument, but you'll again need to have it null-terminated:

call function1(TRIM(filapp)//c_null_char)

The trim is to avoid having trailing blanks before the termination.

Alternatively, have the null character in filapp by some means.

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