我写了这段代码.我想向用户询问文件的完整路径,然后转到该路径并打开文件.但不幸的是程序无法找到该文件.例如,我在这个路径G:\ project 2 \newfile中创建了一个文件但是当我在c ++控制台中输入它时,它说"打开文件时出错".我真的需要解决这个问题.请帮我解决一下这个.谢谢
#include <iostream>
#include <fstream>
#include <conio.h>
#include <windows.h>
using namespace std;
int main()
{
string address;
cout << "Enter the full path of the file" << endl;
cin >> address;
ifstream file(address.c_str());
if (!file) {
cout << "Error while opening the file" << endl;
return 1;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您的应用程序失败,因为您没有正确处理文件名中的空格.
试试这个而不是cin >> address;:
getline(cin,address);
Run Code Online (Sandbox Code Playgroud)
看到这个问题cin和getline.之间的区别.