Tova
Tova

Reputation: 25

C++ trouble reading txt file

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!

Upvotes: 0

Views: 210

Answers (1)

Pete Becker
Pete Becker

Reputation: 76523

"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.

Upvotes: 1

Related Questions