【发布时间】:2019-11-18 14:37:20
【问题描述】:
我正在尝试打开一个路径包含非 ascii 字符的文件。用户将文件拖到 cmd 中,我使用 getline 获取路径。 当我尝试使用用户提供的路径打开文件时,它不起作用。
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
string userInput; //Saves the user input
string autoInput = "C:\\Espolón\\file.txt"; //Specifying the path like this works
ifstream file1; //For opening the file with the userInput
ifstream file2; //For opening the file with autoInput
getline(cin, userInput);
system("CLS"); //Clears the CMD
file1.open(userInput); //This throws an error. Note that I didn't use is_open for cleaner code but im actually using it in my tests
file2.open(autoInput); //This works perfectly
cout << "User input: " + userInput << endl<<"Auto input: " + autoInput << endl; //Both show correctly in the CMD
system("pause");
}
虽然 cout 正确显示了所有内容,但在调试时我发现 userInput 非 ascii 字符 'ó' 正在更改为 '¢' ("C:\Espol¢n\file.txt") 但自动输入是正确存储(“C:\Espolón\file.txt”): screen capture. 因此,如果文件有特殊字符,我无法使用用户提供的路径打开文件。
我尝试使用在其他类似问题中读到的宽字符:
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
wstring userInput; //Saves the user input
string autoInput = "C:\\Espolón\\file.txt"; //Specifying the path like this works
ifstream file1; //For opening the file with the userInput
ifstream file2; //For opening the file with a fix string
getline(wcin, userInput);
system("CLS"); //Clears the CMD
file1.open(userInput); //This throws an error. Note that I didn't use is_open for cleaner code but im actually using it in my tests
file2.open(autoInput); //This works perfectly
wcout << L"User input: " + userInput << endl;
cout<<"Auto input: " + autoInput << endl; //Both show correctly in the CMD
system("pause");
}
但问题仍然存在。 我也尝试将编码更改为 Unicode,但没有任何改变。
欢迎任何帮助! (对不起,英语不好)
【问题讨论】:
-
您是否尝试过使用
std::string、cout和cin的宽字符版本? -
对我来说,您的代码有效。 (甚至是第一个版本)
-
@ThomasMatthews 是的!那是在第二个代码块中。
-
@n314159 您是否尝试过使用非 ascii 字符的路径?您使用的是哪个 IDE?我正在使用 Visual Studio Community 2019。