【问题标题】:File Handling C++ Error文件处理 C++ 错误
【发布时间】:2013-06-25 11:48:00
【问题描述】:

我想编写一个程序,允许用户编写一些随机的东西,但我得到了一个 说错了

 没有对 
的匹配调用,我无法弄清楚。请帮我。 当您尝试回答这个问题时,请尝试更加具体。

这是我的代码

#include<iostream>
#include<fstream>
#include<string>

using namespace std;

int main()
{
    string story;
    ofstream theFile;
 theFile.open("Random.txt");
 while(cin.get(story,5000)!=EOF)
{
    theFile<< story;
}
return 0;
}

【问题讨论】:

  • 您遇到了什么错误?
  • 没有匹配的调用“std::basic_istream::get(std::) 等等”
  • 检查the documentation - 没有istream::get 的过载导致std::string

标签: c++ string file cin


【解决方案1】:

带有 2 个参数的 cin.get 需要 char* 作为第一个参数,而您尝试将 string 作为第一个参数传递。

如果您想在行尾阅读 std::string 而不是 C 字符串,请使用 getline(cin, story)

如果您想在下一个空格或换行符或另一个空白符号之前读取字符串,请使用cin &gt;&gt; story;

【讨论】:

    【解决方案2】:

    您似乎正在尝试将 cin 的内容写入文件。您可以只使用流运算符:

    #include <iostream>
    #include <fstream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
      string story;
      ofstream theFile;
      theFile.open("Random.txt");
    
      if(cin >> story)
      {
        theFile << story.substr(0, 5000);
      }
    
      return 0;
    }
    

    我假设您只想要 Random.txt 中的前 5000 个字符...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 2013-05-12
      • 2013-10-17
      • 1970-01-01
      • 2018-04-21
      相关资源
      最近更新 更多