-1

我在打开名称中有空格的 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()在空格后不能读取多个字符串。我正在考虑使用子字符串,但我不完全确定如何进行。你们能帮帮我吗?

4

1 回答 1

0

你试过这个吗(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 字符组成。

于 2012-09-25T05:03:49.313 回答