August 12th, 2013, 06:45 AM
C++ vector lineparser
I'm trying to code some C++ program that makes a vector open a file, and print each line with its number.
But its just not printing anything. By the way the .txt is in the same directory and I made a similar program with vectors made of floats but that doesn't open files.
using namespace std;
int main(int argc, char * argv)
for(int i = 0; i < v.size(); i++)
cout << i << " " << v[i] << endl;
Some insight? Thanks
EDIT: Now made it a project on code::blocks and put the .Txt in the .Exe repertory, and avg says its a virus...
August 12th, 2013, 08:26 AM
You should be checking that the file opens correctly and take action if it doesn't.
This is probably being caused because of where you are placing your projects.
What directory are you using for your projects?
August 12th, 2013, 09:02 AM
Am I forced to check if the file exist ? Because I saw the solution of my book "Thinking in C++" and it's exactly the same except no .close();
My repertory is in my documents.
So should I use assert or some other thing ? I haven't seen how to check errors yet :/
August 12th, 2013, 09:10 AM
It's considered a good practice to always check the return values of standard functions. These return values usually will tell you why things aren't working properly.
The easiest way to check for stream errors is with an if statement:
Do you know that you don't need to explicitly close the stream in C++? The class destructor will properly close the file when the file goes out of scope.
// Check the stream state to insure the file opened.
// The file failed to open properly. Tell the user, then take some appropriate action.
August 12th, 2013, 09:22 AM
Thanks a lot Jim !
I added the file checking "if(!in)" and I put "cout << "Failed to open file" << endl;" inside, and now it always tell me I failed to open file in the console output !. I don't really understand, its the exact same name of the file, in the same repertory Release of my project of code::blocks, so .exe and .txt are in same directory and its still not working... Maybe I need to add the full path of the file (I tried) ? Or to put \\(or some other character) before linetest.txt ?
Thanks in advance
EDIT: realised we need to have a char * but its still not working. Please don't answer here but on my new topic "class that read file and put them in a string" !