Home > Blockchain >  How to make lambda for this function?
How to make lambda for this function?

Time:11-14

I am wondering how to make a lambda in C for this function and the type has to be void

void setIO(string s){
   freopen((s ".in").c_str(),"r",stdin);
   freopen((s ".out").c_str(),"w",stdout);
}

CodePudding user response:

You can specify the type like so:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    const string FILE_NAME = "test.txt";
    
    auto f = [](string const &name) -> void {
        ofstream file;
        file.open(name);
        file << "junk\n" << "junk2" << endl;;
        file.close();
    };
    
    f(FILE_NAME);
    
    ifstream inputFile(FILE_NAME);
    if (inputFile.is_open()) {
        cout << "File is open." << endl;
        string line;
        while (getline(inputFile, line))
            cout << line << '\n';
        cout << flush;
        inputFile.close();
    } else
        cerr << "Error opening file." << endl;
    
    return EXIT_SUCCESS;
}

However, lambda functions can deduce the return type, so you can leave out -> void.

auto f = [](string const &name) {
        ofstream file;
        file.open(name);
        file << "junk\n" << "junk2" << endl;;
        file.close();
    };

CodePudding user response:

The equivalent way to create a lambda would be:

auto f = [](string s) -> void { 
        //freopen((s ".in").c_str(),"r",stdin);
        //freopen((s ".out").c_str(),"w",stdout);
        std::cout<<"inside lambda"<<std::endl;
        
        //some other code here
        
    };

Now you can use/call this as:

f("passing some string");
  • Related