我在 C++ 中打开名称中包含空格的文件时遇到问题。例如,打开文件
read me.txt
。
这是我迄今为止涉及一个读取文件并将字数统计输出到控制台的命令的代码:
string choice, word, fname;
ifstream input;
int l, count = 0;
if(choice == "wc" || choice == "WC" || choice == "Wc")
{
getline(cin, fname);
input.open(fname.c_str());
cout << fname << endl;
if(input.fail())
{
cerr << " Error: failed to open the file: " << fname << endl;
input.clear();
}
else
{
w = 0;
while (input >> word)
w++;
input.close();
count = w;
cout << fname << " has a Word Count of: " << count << " words \n" << endl;
}
}
我知道流函数
c_str()
无法读取空格后的多个字符串。我正在考虑使用子字符串,但我不完全确定如何继续。你们能帮我一下吗?
你尝试过这个吗(http://www.cplusplus.com/forum/beginner/39687):
在文字字符串中,
\
字符被解释为转义码,以允许您嵌入无法输入或不可打印的字符。例如,要在文字字符串中嵌入换行符,您不能在键入文字字符串时直接按 Enter 键,因为编辑器会通过实际开始新行来响应。因此,您输入“\n
”,即“This is on the first line \n This is on the second line
”。要输入“\
”字符,您需要通过输入两个斜杠来转义它。第一个斜杠是转义字符,第二个斜杠是嵌入的斜杠字符。
示例:
C:\\Program Files\\filename.txt
编辑: 用户不输入转义字符而只输入文件名。然后程序必须处理空格和路径反斜杠。
\n
指定新行,但它由转义字符后跟 n 字符组成。