0

I can't read a txt file. I've tried with different pieces of code which should work and with different text files. The problem isn't that I got the wrong name (the file doesn't lack a txt or have an extra txt). Also, adding a second backwards slash \ or replacing it with forwards slash / doesn't fix it.

Here is the code:

// ConsoleApplication74.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <fstream> #include <string> using namespace std; #include <iostream> #include <iomanip> #include <fstream> using namespace std; int main() { int sum = 0; int x; ifstream inFile; inFile.open("C:\Users\chaim\SkyDrive\Documents\string\text1.txt"); if (!inFile) { cout << "Unable to open file"; exit(1); // terminate with error } while (inFile >> x) { sum = sum + x; } inFile.close(); cout << "Sum = " << sum << endl; return 0; } 

Thanks!

4
  • Please explain, as completely as possible, what your program does and how that is different from what is desired. Commented Nov 26, 2015 at 18:27
  • I recommend using / in your filenames, because \t is a tab character. Commented Nov 26, 2015 at 18:52
  • 1
    Even if you really like header files, there is no need to include them more than once. Commented Nov 26, 2015 at 18:54
  • Get rid of stdafx and turn off precompiled headers for small programs. The precompiled header feature does not give you any advantages unless you have a huge program with lots of include files or you are writing a Windows program and accessing their API. (The windows.h file is huge and could benefit from being precompiled.) Commented Nov 26, 2015 at 18:56

1 Answer 1

1

"C:\Users\chaim\SkyDrive\Documents\string\text1.txt" should be "C:\\Users\\chaim\\SkyDrive\\Documents\\string\\text1.txt". That way you get backslashes at the appropriate places in the file name.

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

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.