c++ - 读取文件并添加到数组 char

标签 c++ file fstream

#include<iostream>
#include<fstream>
#include<cctype>
#include<string>
using namespace std;

int main(){
    ifstream fin;
    int i,size,j=8,t=0;
    char kunci[21]="TFFTFFTTTTFFTFTFTFTT";
    string data;
    fin.open("datajawaban.txt");
    //getline(fin,data);
    char jawab[31];
    cout <<"ini isi file " <<data<<endl;
    for(i=0;i<=31;i++){
       fin >> jawab[i];
       jawab[31] = '/0';
       if(jawab[j]==kunci[i])t++;
       cout <<"data ke "<<i <<" "<< jawab[j] << " - " <<kunci[i]<<endl;     
       j++;
    }
    cout << "jumlah benar "<< t;
    fin.close();   
    system("pause");
    return 0;
}

这是我的代码

输出是 ±

± ` ( v

p ↨ v

P ☺ v

-

0 \ ± C

P ☺ v

这是错误的输出,我的代码有什么问题?

这次请帮帮我,这是我的功课

最佳答案

jawab[31] = '/0';undefined behaviour由于数组大小为 31,数组索引从 0 开始,最大索引值可以是 size - 1,即 30 for jawab数组。

不仅是你的for循环运行 i<=31; ,你指数i在循环中 kunci[i]因为 i > 19 那是数组超出索引错误的另一个点。 -- 只需声明足够大的数组即​​可纠正这两个错误。

关于c++ - 读取文件并添加到数组 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18806766/

相关文章:

c++ - 从 QThread 中运行的 C 代码显示 QMessageBox

c++ - 使用迭代器对 std::list 进行排序

c++ - 分配 avpkt.size 时,avcodec_decode_video2 崩溃

c - execvp 如何运行命令?

Android:是否可以将 ZIP 文件添加为原始资源并使用 ZipFile 读取它?

c++ - std::ofstream 追加文件

C++ ifstream 将读取一些值然后停止

c++ - 从(成员)函数推导出类型

c - 我的搜索链表实现错误

C++ ifstream 字符串