简体   繁体   中英

Unable to open file.txt with c++

I've looked up similar posts here, but none seem to be doing the job for my question. I'm basically trying take a sequence of words in a .txt file and put each word in a vector, and printing each value afterwards. For example, we have I love racing cars in array.txt , and I want my vector to have "I" at position 0, "love" at 1 and so on. Unfortunately, the code does not access "array.txt", so it never executes the code in the if condition. Now I've heard that by using the fstream library it should work just fine, but the file is never found. I suspect that it doesn't work because it cannot find the path, but I have never opened files in C++. Also, I have not put my file anywhere in my project folder.

Some changes I've already tried:

  • file.open("array.txt");
  • omitting file.close();
  • include "C:\\array.txt"; (with the # in front)
  • file.open("C:\\array.txt")

And I'm using Windows 10, if this matters.

#include <iostream>;
#include <string>;
#include <vector>;
#include <fstream>;
//#include <"C:\Users\Samer El-Hage\Documents">;
using namespace std;

void main(){
    vector<string> v (10);
    ifstream file;
    file.open("C:\array.txt", ios::in);
    if (file.is_open())
    {
        for (int i = 0; i < 3; i++)
        {
            file >> v[i];
        }
        file.close();
    }
    else cout << "Could not access file.";
    for (int i = 0; i < 3; i++)
    {
        cout << v[i] << " ";
    }
}

This code prints "Could not access file."

The file cannot be opened because the file system can't find the file named "[Bell]rray.txt". the character sequence '\\a' is the "Make my computer Beep" character.

Use either forward slashes: "C:/array.txt" , an escaped backslash: "C:\\\\array.txt" or a raw string literal: R"(C:\\array.txt)"

The file must also exist at the specified location. If you do not provide a drive and just say "array.txt" the location defaults to wherever the executable is (or in an IDE, the Working Directory).

Also, you have unnecessary semi-colons after your includes. (In fact, in a Treat Warnings as Errors setup, this won't compile!)

\\a simply turns the computer beep on. Try writing "C:\\\\array.txt" instead in the open call.

I got it! I had not put the .txt file in my folder with the source code, which, strangely enough, was not mentioned in my previous search results... I got to search better!

Try not calling open explicitly:

ifstream file ("array.txt");

Look at the examples here: 1

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