-
Strings and File I/O
Here's some code I have:
Code:
#include <iostream.h>
#include <stdlib.h>
#include <fstream.h>
#include <string.h>
using namespace std;
int main()
{
string Path;
cout << "Enter path of file to be read: ";
cin >> Path;
cout << "\nHere are the contents of that file:\n";
ifstream fin(Path);
char ch;
while(fin.get(ch))
cout << ch;
cout << "\n\nEnd of file!\n";
fin.close();
system("PAUSE");
return 0;
}
When I tried to compile it on Dev-C++ 4, it gave me the error message: 'string' undeclared (first use this function).
When I tried to compile it on Codewarrior 6, I got this error message:
Error : function call 'basic_ifstream(std::basic_string<char, std::char_traits<char>, std::allocator<char>>)' does not match
'std::basic_ifstream<char, std::char_traits<char>>::basic_ifstream()'
'std::basic_ifstream<char, std::char_traits<char>>::basic_ifstream(const char *, std::ios_base::openmode)'
'std::basic_ifstream<char, std::char_traits<char>>::basic_ifstream(const std::basic_ifstream<char, std::char_traits<char>> &)'
hello.cpp line 13 ifstream fin(Path);
What do I do?
-
First,wrong header,string.h is a C header,not the C++ std::string header.
Try
Code:
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
using namespace std;
and....
Code:
ifstream fin(Path.c_str());
-
Thanks, all my problems are gone now.