简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM