I am just learning the very basic aspects of input/output streams, and can't seem to have my program read a text file. It gives me errors that indicate it is trying to read the .txt file as C++ code, while I am just using values in there to test my stream.
These are the contents of my included .txt file:
12345
Success
And here is the main program's code:
#include <fstream>
#include <iostream>
#include "C:\Users\Pavel\Desktop\strings.txt"
using namespace std;
int main (int nNumberOfArgs, char* pszArgs[])
{
ifstream in;
in.open("C:\Users\Pavel\Desktop\strings.txt");
int x;
string sz;
in << x << sz;
in.close();
return 0;
}
The first error message I receive is "expected unqualified-id before numeric constant" which tells me the program is attempting to compile the included file. How can I prevent this and have the text file read as intended?
Don't #include your .txt file. Includes are for source code. They textually insert the file into your code, as if you had actually copy-pasted it there. You shouldn't be #includeing a file you're opening with an ifstream.
Opening files on the filesystem at runtime doesn't require any mention of that file's name in the source code. (You could, for instance, ask the user for a filename, and then open it just fine!)
The case where you might #include data in your source would be if you wanted to have that data embedded into the executable of your program (and thus not rely on a file that was on the filesystem when running). But to do that, you have to format your file as a valid C++ data declaration. So it would not be a .txt file at that point.
For instance, in strings.cpp
#include <string>
// See http://stackoverflow.com/questions/1135841/c-multiline-string-literal
std::string myData =
"12345\n"
"Success";
Then in your main program:
#include <iostream>
#include <sstream>
#include "strings.cpp"
using namespace std;
int main (int nNumberOfArgs, char* pszArgs[])
{
istringstream in (myData);
int x;
// Note: "sz" is shorthand for "string terminated by zero"
// C++ std::strings are *not* null terminated, and can actually
// legally have embedded nulls. Unfortunately, C++ does
// have to deal with both kinds of strings (such as with the
// zero-terminated array of char*s passed as pszArgs...)
string str;
// Note: >> is the "extractor"
in >> x >> str;
// Note: << is the "inserter"
cout << x << "\n" << str << "\n";
return 0;
}
Generally speaking, just #include-ing a source file like this is not the way you want to do things. You'll quickly run into trouble if you do that in more than one file in your project (duplicate declarations of myData). So the usual trick is to separate things into header files and implementation files...including the headers as many times as you want, but only putting one copy of the implementation into your build process.
An #include directive works the same way regardless of the extension of the file being included - txt, h, no extension at all - it doesn't matter. How it works is the contents of the file are pasted into your source file by the preprocessor before that file is passed to the compiler. As far as the compiler is concerned, you might as well have just copied and pasted the contents yourself.
Related
I have two similar methods that open a file identically, but process them and return values a bit differently, yet while the first method does that successfully, the second method, which is called after the first one, fails.
I have tried changing the path to this file, its extension, but I think I miss some important knowledge about ifstream.
vector<User> Database::createUserDatabase()
{
vector<User> users;
ifstream inputFile;
inputFile.open(pathToFile, ios::in);
//Some file processing
inputFile.close();
return users;
}
And that works perfectly, while
vector<User> Database::createBookDatabase()
{
vector<Book> books;
ifstream inputFile;
inputFile.open(pathToFile, ios::in);
//Some file processing
inputFile.close();
return books;
}
fails to end whenever I check if the file has been opened or not using
inputFile.is_open()
These functions are defined in class files Database.cpp, User.cpp, Book.cpp, which are correctly linked to the main.cpp with the following content:
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <sstream>
#include <vector>
#include <fstream>
#include "../lib/Book.h"
#include "../lib/User.h"
#include "../lib/Database.h"
using namespace std;
int main()
{
Database userDatabase("../database/users.txt", "users");
Database bookDatabase("../database/lmsdb.txt", "books");
vector<User> users = userDatabase.createUserDatabase();
vector<Book> books = bookDatabase.createBookDatabase();
return 0;
}
Here are my Project directories
Using gdb debugger, I have confirmed that the file is not being opened at all. I assume that I did not close the files properly, but I have a little knowledge of C++ yet (been learning it for only a week or so).
Looking forward to see what you can suggest reading/researching, yet I really would like to see a straightforward solution to this problem.
I assume that I did not close the files properly, [..]
Yes, but that probably isn't the cause of the issue. The C++ way is to not close them explicitly. Due to RAII, the ifstream will close itself once it goes out of scope (i.e. when the enclosing function terminates).
There are many reasons why a file could fail to open, including:
It doesn't exist.
Trying to open a read-only file in write mode.
The file is in use by another process. (Maybe you have it opened in an editor?)
Insufficient privileges (e.g. due to the file being protected).
#include <istream> //Includes the input/output library
using namespace std; // Makes std features available
// The main function of the program
// It outputs the greeting to the screen
int main() {
count <<"Hello World! I am C++ Program." <<endl;
return 0;
}
IntelliSense: no operator message Line 7, Column 8
error C2563:mismatch in formal parameter list Line 7, Column 1
Replace #include <istream> with the correct header, #include <iostream>.
Helpful mnemonic:
io = input/output
stream = "stream of data"
Additionally, the name of the standard output stream is std::cout or cout with the std:: namespace scope removed.
Helpful mnemonic:
std:: = Standard library's
cout = console output
The problems you are having with your simple block of code is simply: spelling errors.
Firstly, you have misspelled the input/output stream file in your include statement, so you need to rename the header file to:
#include <iostream>
There is no heade file named istream.
Secondly, you also misspelled the cout function to count. Change that line to:
cout << "Hello World! I am C++ Program." << endl;
Those lines should work now.
Also a recommendation for your future programs; avoid using the line
using namespace std;
Why? Because as you move on to more complex programming, you will undoubtedly learn and begin to define a data type or variable, and sometimes, that name may also be used by the standard library. As a result, you will have a hard time trying to differentiate the variables or data types you defined and the ones defined in the std library.
Therefore, try and attach std:: before every function that is a part of the standard library.
EDIT:
The code you posted in the comments box is pretty unreadable, so I just fixed it and have posted it below:
#include <iostream> //Includes the input/output library
using namespace std; // Makes std features available
// The main function of the program
// It outputs the greeting to the screen
int main()
{
cout <<"Hello World! I am C++ Program." <<endl;
return 0;
}
I've tried this in my IDE and fixed with the same and only recommendations from above. It works for me.
In my code below errors occur and the program will not run, I am required to make a Constructor that must open the file with the given filename. If the filename does not exist then it Prints an error message and terminates the program.
Below is the code that I have done so far in C++:
#include "ReadWords.h"
#include <iostream>
#include <cstdlib>
using namespace std;
ReadWords::ReadWords(const char filename[])
{
wordfile.open(filename);
if (!wordfile)
{
cout << "cannot make " << filename << endl;
exit(1);
}
}
void ReadWords::close()
{
wordfile.close();
}
Why dont you try including fstream to the top of your file and see if that works
I suppose wordfile is of type std::fstream. If your ReadWords.h #includes <fstream>, it should work (compiles and works as expected).
By the way, it's a bad practice to use using namespace std;.
Also, since you use C++, take a look at std::string. It's safer than using plain char* or char[].
I have a program that reads in a file. All my classes compile fine, but there seems to be an error when I read in the file. Eclipse shows an empty string is being read in (""), which is not what I want.
I have the code for my main below with a while loop. I placed the loop just to see how it would run when debugging, and it runs an infinite loop since it is always reading in "", and never reaches end of file. I have put the file in the working directory and every other folder just to be sure, but it is always doing this even though the file is full of strings and integers. Is there anything I am doing wrong here?
#include "Translator.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
ifstream readFile;
readFile.open("sample.html");
while (!readFile.eof()) // for debugging purposes only
{
string x;
readFile >> x; // x is "" everytime through the loop
readFile >> x; // x is also ""
}
Translator t(readFile);
readFile.close();
return 0;
}
My guess is that your file did not actually open, and the eof bit was therefore not set. You never test whether the file was opened successfully. It could be that your working directory is not what you think it is, or the file is locked by another process (perhaps open in a text editor).
Officially, you can test readFile.fail() after you try opening.
I've found that checking readFile.good() is fine too - in fact you can use that as your loop condition.
I prefer the positive message of 'good' in my code, rather than the potentially upsetting 'fail'.
You should also test your stream as WhozCraig suggested in comments, when you are reading data. You cannot assume that the operation was successful. If it fails for reasons other than EOF, you need to know.
For these reasons, don't use readFile.eof() as your loop condition.
I have really strange problem. In Visual C++ express, I have very simple code, just:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}
This same code works OK in my one project, but when I create now project and use this same lines of code, no file test.txt is created. Please, what is wrong?ยจ
EDIT: I expect to see test.txt in VS2008/project_name/debug - just like the first functional project does.
Canonical code to write to a file:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ofstream file;
file.open("test.txt");
if ( ! file.is_open() ) {
cerr << "open error\n";
}
if ( ! ( file << "Hello" ) ) {
cerr << "write error\n";
}
file.close();
}
Whenever you perform file I/O you must test every single operation, with the possible exception of closing a file, which it is not usually possible to recover from.
As for the file being created somewhere else - simply give it a weird name like mxyzptlk.txt and then search for it using Windows explorer.
Perhaps the executable is run in a different directory than it was before, making test.txt appear somewhere else. Try using an absolute path, such as "C:\\Users\\NoName\\Desktop\\test.txt" (The double backslashes are needed as escape characters in C strings).
fstream::open() takes two arguments: filename and mode. Since you are not providing the second, you may wish to check what the default argument in fstream is or provide ios_base::out yourself.
Furthermore, you may wish to check whether the file is open. It is possible that you do not have write permissions in the current working directory (where 'test.txt' will be written since you don't provide an absolute path). fstream provides the is_open() method as one way of checking this.
Lastly, think about indenting your code. While you only have a few lines there, code can soon become difficult to read without proper indentation. Sample code:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios_base::out);
if (not file.is_open())
{
// Your error-handling code here
}
file << "Hello";
file.close();
}
You can use Process Monitor and filter on file access and your process to determine whether the open/write is succeeding and where on disk it's happening.
Theres two ways to fix this. Either do:
file.open("test.txt", ios::out)
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open("test.txt", ios::out);
file<<"Hello";
file.close();
}
Or you can create an ofstream instead of fstream.
#include <fstream>
using namespace std;
int main()
{
ofstream file;
file.open("test.txt");
file<<"Hello";
file.close();
}