【问题标题】:C++: File I/O having difficulty with opening and working with itC++:文件 I/O 难以打开和使用它
【发布时间】:2013-10-15 01:55:37
【问题描述】:

我在打开文件和处理其中的内容时遇到了困难。我想做的是

  1. 从输入文件中拉一行

  2. 使用该行初始化 istreamstream

  3. 从字符串流中提取每个单词

    我。处理单词

    • 执行我创建的特定功能

    二。将其写入输出文件

我不知道该怎么做 1-3 谁能帮助我的功能?这就是我目前所拥有的......

string process_word(ifstream &inFile){
    string line, empty_str = "";
    while (getline(inFile,line)){
        empty_str += line;
    }
    return empty_str;
}

int main(){
    string scrambled_msg = "", input, output, line, word, line1, cnt;
    cout << "input file: ";
    cin >> input;
    cout << "output file: ";
    cin >> output;

    ifstream inFile(input);
    ofstream outFile(output);

    cout << process_word(inFile);
}

【问题讨论】:

  • 对C++不太好,真的可以使用帮助!谢谢大家
  • 那么你的问题是什么?
  • 我的 process_word 函数无法工作,所以它输出的是文件中的单词!
  • 您的process_word 函数会读取文件的全部内容。我没有看到任何处理这些单词的尝试。您是否要求我们为您做这部分?
  • 那我应该如何处理这些单词呢?

标签: c++ file function c++11 iostream


【解决方案1】:
std::vector<std::string> process_word(std::ifstream& in)
{
    std::string line;
    std::vector<std::string> words;

    while (std::getline(in, line)) // 1
    {
        std::istringstream iss{line}; // 2

        std::move(std::istream_iterator<std::string>{in},
                  std::istream_iterator<std::string>{},
                  std::back_inserter(words));
    }

    return words;
}

int main()
{
    std::ifstream in(file);
    std::ofstream out(file);

    auto words = process_word(in);

    for (auto word : words)
        // 3 i.

    std::move(words.begin(), words.end(), // 3 ii.
              std::ostream_iterator<std::string>{out});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2018-02-02
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多