读取函数由 main 调用,但不执行
Reading function is called by main, but not executed
这个文件从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
}
相关文章:
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 为什么即使调用了析构函数,C++11 中的分离线程也可以执行
- 无法调用成员函数,尝试正确执行此操作仍然失败
- 不执行任何操作的函数调用C++
- 在 c++ 托管和异步运行中调用 c# 可执行文件
- 调用函数一次用于动态链接库,一次从可执行文件调用函数
- 如何执行参数化构造函数的调用?
- 当再次触发信号时,从Qt插槽执行的功能被第二次调用时会发生什么?
- 在可变函数调用中执行一次语句
- 如何在派生类中不显式调用base::func()的情况下从基类执行虚拟函数
- 只有一个可执行文件即可进行跨平台 SIMD 调用?
- 调用函数来创建 WinAPI 按钮不会执行任何操作
- 从 PHP 调用已编译的C++可执行文件来创建套接字
- 如何让派生类在调用基类之前执行操作?
- 在 MySQL 连接器C++ API 中使用一个函数调用执行多个查询的正确方法是什么?
- 在链接的程序集文件中,我想从 c++ 调用代码访问变量.是否可以在不触发访问冲突的情况下执行此操作?
- 仅执行一次函数一次内部循环,该循环在每个0.1秒C 处都被调用
- 如何测试基类中的方法是否已使用谷歌模拟调用和执行?
- 编译器是否对所有内联函数调用执行相同的操作
- 动态执行的 ARM ASM 系统调用,可从C++重新定位