How to use string in C++?

Asked

Viewed 201 times

3

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));
}

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

variable 'Std::ifstream check' has initializer but incomplete type

I use Codeblocks to program.

  • 1

    Not that it’s the cause of the problem, but you have some reason to use the c_str()? Try adding: #include <fstream>

  • Which version of C++ are you using? (C++11 or C++98) because they have right constructors.

  • 1

    Wouldn’t a second parameter be required for this constructor? because depending on its objective it will be necessary to pass a second parameter http://www.cplusplus.com/reference/fstream/ifstream/ifstream/

  • Solved the problem with the solution I gave you?

  • Yes, you did. Thank you very much, beast.

  • As for the C++ version, I have no idea. What is the best program for C++. Codeblocks? Visual Studio?

  • @Marcelonascimento does not have the best program, that is taste, each one has its advantages and disadvantages. Either way these programs you talked about are just the IDE and not the compiler, although each of them comes with specific compilers.

Show 2 more comments

1 answer

2


The problem is that you do not include the required header in case 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));
}

Behold functioning (approximately) in the ideone. And in the repl it.. Also put on the Github for future reference.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.