【问题标题】:Read an entire line including spaces from fstream从 fstream 中读取包括空格在内的整行
【发布时间】:2013-01-24 21:45:28
【问题描述】:

我目前正在做一个 C++ 的小项目,现在有点困惑。我需要从使用 ifstream in() 的文件中读取一行中的一定数量的单词。它现在的问题是它一直忽略空格。我需要计算文件中的空格数量来计算字数。反正有 in() 不忽略空格吗?

ifstream in("input.txt");       
ofstream out("output.txt");

while(in.is_open() && in.good() && out.is_open())
{   
    in >> temp;
    cout << tokencount(temp) << endl;
}

【问题讨论】:

  • 能否在问题中包含代码 sn-p?当问题更清楚时,答案会更具体。
  • 你可以配置 C++ 流是否应该忽略空格,如果我没记错的话,它叫做“skipws”。
  • 虽然条件如此愚蠢,但我什至不知道如何评论它。你甚至fstream::operator bool()
  • @Griwes 的意思是你可以做 while(in) {...}

标签: c++ fstream


【解决方案1】:

计算文件中的空格数:

std::ifstream inFile("input.txt");
std::istreambuf_iterator<char> it (inFile), end;
int numSpaces = std::count(it, end, ' ');

要计算文件中空白字符的数量:

std::ifstream inFile("input.txt");
std::istreambuf_iterator<char> it (inFile), end;
int numWS = std::count_if(it, end, (int(*)(int))std::isspace);

作为替代方案,您可以计算 字数,而不是计算 空格

std::ifstream inFile("foo.txt);
std::istream_iterator<std::string> it(inFile), end;
int numWords = std::distance(it, end);

【讨论】:

  • +1 用于 istreambuf_iterator 技巧。我想知道是否有一些东西可以让你用一个迭代器来完成整个文件:)
【解决方案2】:

我会这样做:

std::ifstream fs("input.txt");
std::string line;
while (std::getline(fs, line)) {
    int numSpaces = std::count(line.begin(), line.end(), ' ');
}

一般来说,如果我必须为文件的每一行做一些事情,我发现 std::getline 是最不挑剔的方法。如果我需要来自那里的流运算符,我最终会从那条线中制作一个字符串流。这远不是最有效的做事方式,但我通常更关心的是把它做好并为这类事情继续生活。

【讨论】:

    【解决方案3】:

    您可以将countistreambuf_iterator 一起使用:

    ifstream fs("input.txt");
    
    int num_spaces = count(istreambuf_iterator<unsigned char>(fs),
                           istreambuf_iterator<unsigned char>(),
                           ' ');
    

    编辑

    最初我的回答使用了istream_iterator,但正如@Robᵩ 指出的那样,它不起作用。

    istream_iterator 将遍历一个流,但假定空白格式并跳过它。我上面的示例使用istream_iterator 返回结果为零,因为迭代器跳过了空格,然后我要求它计算剩余的空格。

    istreambuf_iterator 但是一次只接收一个原始字符,不能跳过。

    请参阅istreambuf_iterator vs istream_iterator 了解更多信息。

    【讨论】:

    • code 并没有像你想象的那样做。事实上,它总是返回零。
    • 感谢您的反馈,@Robᵩ
    猜你喜欢
    • 2010-09-12
    • 1970-01-01
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 2013-02-28
    相关资源
    最近更新 更多