【问题标题】:C++ input from array to file through function通过函数从数组到文件的C++输入
【发布时间】:2013-11-17 12:14:41
【问题描述】:

我目前正在学习基本的c++,我遇到了一个我无法处理的问题。在下面的代码中,您可以看到我的程序。不好的是,从cout << word; 我可以看到我的文本文件的内容,但cout << astring 没有显示任何内容。谁能指出我的错误?
附:必须用函数来完成。

void read(string word);
int main()
{

string astring;
read(astring);
cout << astring;

return 0;
}
void read(string word)
{
ifstream duom ("info.txt");

if (duom.is_open())
{


while(!duom.eof()) 
{

    getline(duom, word);
    cout << word;
}
}
else cout << "File couldn't be opened";
}

【问题讨论】:

    标签: c++ string file function


    【解决方案1】:

    您的函数read 将复制到字符串并读入这个临时文件。要读入输入参数,请使用如下引用:

    void read(string& word);
    

    【讨论】:

      【解决方案2】:

      问题是read函数没有改变main中的astring,astring被传递给read函数它不是从read函数返回的。您应该像这样更改阅读方式

      void read(string& word); // pass a reference to a string to read
      
      int main()
      {
          string astring;
          read(atring);
      

      或者像这样

      string read(); // return a string from read
      
      int main()
      {
          string astring = read();
      

      通常首选第二个版本。

      【讨论】:

        【解决方案3】:

        尝试传递对函数的引用:void read(string&amp; word);,以便您以后可以使用实际word,而不是其本地副本。

        【讨论】:

          【解决方案4】:

          你应该使用引用或指针

          void read(string& word); 
          or
          void read(string *word);
          

          【讨论】:

            猜你喜欢
            • 2015-01-25
            • 2017-09-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-05
            • 1970-01-01
            • 1970-01-01
            • 2019-02-27
            相关资源
            最近更新 更多