读取函数由 main 调用,但不执行

Reading function is called by main, but not executed

本文关键字:执行 调用 函数 main 读取      更新时间:2023-10-16

这个文件从AD.txt读取一些数据,将其存储到一个字符串中,并将字符串写入AD受试者.txt。我的写入函数似乎工作正常,但我的读取未被调用。它甚至没有进入读取函数来打印cout语句。我假设如果我只是简单地放置调用函数,它应该会自动出现。这是我的代码:

#include <iostream>
    #include<fstream>
    #include <string.h>
    #include<iomanip>
    #include <cstdlib>
    #define rmax 15
    using namespace std;
    string data1;

读取功能:

    void readSubjects(){
        cout<<"inside read"<<endl;
        ifstream is;
        is.open("AD.txt"); //opening the file
        cout<<"open text"<<endl;
        while(!is.eof()){
            char line[rmax];
            cout<<line<<endl;
            data1 += """;
            is.getline(line,rmax);
            for(int i=0; i<11;i++){
                data1 += line[i];
            }
            data1 += "" \ ";
        }
      is.close();
    }

写入功能:

    void writeSubjects(){
        ofstream os;
        os.open("ADsubjects.txt",ios::out);
        os<<data1;
        os.close()
    }

主要功能:

    int main() {
        readSubjects();
        cout<<"read"<<endl;
        writeSubjects();
        cout<<"written"<<endl;
        cout << "Hello, World!" << endl;
        return 0;
    }

在此代码中;有很多问题。

os.close()中的编译问题 - 缺少分号

char line[rmax];cout<<line<<endl;代码是错误的,因为它没有初始化。打印未初始化的变量可能会弄乱您的终端。

实际上,阅读行正确读取了该行。为什么要使用 for 循环从行将 11 个字符复制到 data1?示例中允许的最大长度为 15。你可以这样说。

data1 += line;

以下代码将起作用。

void readSubjects(){
        cout<<"inside read"<<endl;
        ifstream is;
        is.open("AD.txt"); //opening the file
        cout<<"open text"<<endl;
        while(!is.eof()){
            char line[rmax];
//            cout<<line<<endl; // This is wrong
            data1 += """;
            is.getline(line,rmax);
 //           for(int i=0; i<11;i++){
 //               data1 += line[i];
 //           }
            data1 += line;
            data1 += "" \ ";
        }
      is.close();
    }

在读取的 while 循环中,您需要做的就是:

    while(is){  //the is will run until it hits the end of file.
      //code here
    }  

如果 readSubjects() 根本没有被调用,那么可能需要在 int main() 上方声明函数原型,而实际的函数声明应该在 int main() 下声明,如下所示:

    void readSubjects();

    int main(){
      readsubjects();
      //more code...
    }

    void readSubjects()
    {
      //actual function code
    }