简体   繁体   中英

C++ Visual Studio won't read .txt files

I am trying to read each line of a .txt file from the command line arguments in Visual Studio. This is the code I have been using:

ifstream inFile(argv[2]);     //read text file indicated by argv[2]

if (inFile.is_open() && inFile.good())
{
    string line = "";
    while (getline(inFile, line))
    {
        cout << line << '\n';
    }

}

However, whenever I compile this code, I always get garbage characters. The funny thing is that the code works just fine and does what it's supposed to do when I run it directly from terminal. It's only when I use VS that I get this issue. I would appreciate any feedback as to why this is happening. Thank you!

I expect (99.9% likely) that your current working directory is different when you run in Visual Studio. There are two simple options.

  1. Put the file that you are trying to open in the Debug/Release folder in Visual Studio (or wherever its running from)
  2. Change the path you provide in argv[2] to be a full path or a relative path that works for Visual Studio.

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