Colocar uma corda em um ifstream Método [duplicado]
Pergunta
Esta questão já tem uma resposta aqui:
Estou aprendendo C ++ e eu estou recebendo alguns problemas quando eu estou tentando usar um string em ifstream método, assim:
string filename;
cout << "Enter the name of the file: ";
cin >> filename;
ifstream file ( filename );
Aqui está o código completo:
// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;
int main ( int argc, char** argv )
{
string file;
long begin,end;
cout << "Enter the name of the file: ";
cin >> file;
ifstream myfile ( file );
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "File size is: " << (end-begin) << " Bytes.\n";
return 0;
}
E aqui está o erro do Eclipse, o x antes que o método:
no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)'
Mas quando eu tento compilar em Eclipse que colocar um x antes que o método, que indica um erro na sintaxe, mas o que está errado na sintaxe? Obrigado!
Solução
Você deve passar char*
ao construtor ifstream
, use a função c_str()
.
// includes !!!
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string filename;
cout << "Enter the name of the file: ";
cin >> filename;
ifstream file ( filename.c_str() ); // c_str !!!
}
Outras dicas
O problema é construtor que de ifstream não aceita uma string, mas uma seqüência c-style:
explicit ifstream::ifstream ( const char * filename, ios_base::openmode mode = ios_base::in );
E std::string
tem nenhuma conversão implícita de seqüência c-estilo, mas um explícito:. c_str()
Use:
...
ifstream myfile ( file.c_str() );
...
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow