读取文件并添加到数组字符

Read file and add to array char

本文关键字:数组 字符 添加 文件 读取      更新时间:2023-10-16
#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';是未定义的行为,因为数组大小为 31,数组索引从 0 开始,最大索引值可以是大小 - 1 对于jawab数组为 30。

不仅如此,您的for循环运行i<=31;,您在循环kunci[i]中索引i i> 19 这是索引错误之外的另一个数组点。 -- 只需声明足够大的数组来纠正这两个错误。