1

There is a file in directory and i'm trying to read a file but i can't. What is wrong with my code. Example is taken from http://www.cplusplus.com/forum/beginner/37208/

 #include <iostream> #include <fstream> #include <string> #define MAX_LEN 100 using namespace std; string inlasning () { string text; string temp; // Added this line ifstream file; file.open ("D:\education\Third course\semestr 2\security\lab1.2\secret_msg.txt"); while (!file.eof()) { getline (file, temp); text.append (temp); // Added this line } cout << "THE FILE, FOR TESTING:\n" // For testing << text << "\n"; file.close(); return text; } void main () { inlasning(); } 
1
  • Remember that \ in a string makes whatever follows it "special" Commented Feb 18, 2012 at 11:28

3 Answers 3

4

Change \ to \\ in file path. (or to /)

Sign up to request clarification or add additional context in comments.

3 Comments

OP did not say if he/she is working with Windows/Linux/Mac. Does "/" work everywhere?
Ah yes, but I am curious, does forward slash ("/") work in Windows? I remember it did not work when I had tried the same long back...
Forward slash in path works on windows, I just checked it in Codeblock IDE 10.05
1

In string literals \ is used as an escape character.

You have to write \\.

Note: you should check the open call.

On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.

Comments

0

\ is an escape character, so you need to use \\ to obtain the result you intend. This is true almost everywhere, even here in stackoverflow where you nee to use it in order to write something like this for example:

*A*

(just put the \ before the *), otherwise (if you don't use the \) stackoverflow will interpret the text and will output an italic A, this:

A

The same is true for bold (two asterisks... two slashes):

**A**

instead of

A

:)

... or maybe you cannot read it because it is a "secret_msg" :P (LOL)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.