How to use string in C++?

Question:

I'm having trouble dealing with string .

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;

bool ArqExiste(string Arquivo)
{
    ifstream verificacao (Arquivo.c_str());
    if(verificacao.is_open())
    {
        verificacao.close();
        return true;
    }
    else
    {
        verificacao.close();
        return false;
    }
}

int main()
{
    string file = "C:\\Temp\\aipflib.log";

    printf("%b", ArqExiste(file));
}

In the line ifstream verificacao (Arquivo.c_str()) , it gave the error:

variable 'std::ifstream verification' has initializer but incomplete type

I use Codeblocks to program.

Answer:

The problem is that you don't include the necessary header in the #include <fstream> .

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;

bool ArqExiste(string Arquivo) {
    ifstream verificacao (Arquivo.c_str());
    if(verificacao.is_open()) {
        verificacao.close();
        return true;
    } else {
        verificacao.close();
        return false;
    }
}

int main() {
    string file = "C:\\Temp\\aipflib.log";
    printf("%b", ArqExiste(file));
}

See working (approximately) in ideone . And on repl.it. Also posted on GitHub for future reference .

I also removed the conio which luckily is not being used in this code. This header should never be used in modern code.

Also consider not using c_str() there, it is not necessary.

Scroll to Top