简体   繁体   中英

Function to Return output from text file

I am a complete C++ newbie (Python is all i know) and i am trying to figure out what i am doing wrong. This tutorial shows me how to output a text file ( http://www.cplusplus.com/doc/tutorial/files/ )

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

And then when i try to apply this it gives me a

// basic file operations
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string WriteTXT( string DATA , string F_NAME)
{
    ofstream myfile;
    myfile.open (F_NAME.c_str());
    myfile << DATA;
    myfile.close();
}

string ReadTXT( string F_NAME )
{
    string line;
    ifstream myfile (F_NAME.c_str());
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            getline (myfile,line);
            cout << line << endl;
        }
        myfile.close();
    }
    else cout << "Unable to open file"; 
}

int main () {
  WriteTXT("12345","example.txt");
  ReadTXT("example.txt");
  return 0;
}

What on earth?

You need to have:

// returns void
void WriteTXT( string DATA , string F_NAME)
// ...

// returns void
void ReadTXT( string F_NAME )

because you are not returning anything from these functions. If you compile with -Wall and -Werror you can prevent common problems like this one.

使函数的return类型void则它将起作用。

Make return type as void like

void WriteTXT( string DATA , string F_NAME)

void ReadTXT( string F_NAME )

Then it will work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM