从文件中读取,将值插入到整数和字符C++

Reading from file inserting values into ints and chars C++

本文关键字:整数 字符 C++ 插入 文件 读取      更新时间:2023-10-16

我想用密钥从外部文件中读取短二进制文件。

3 A 0100 3 E 0101 3 G 0110 3 M 0111 3 N 1010

3 H 1011 2 S 100 1 T 00 210 2 I 111

3 在名为 POS 的整数中

A 在名为 al 的字符中

0100 在一个名为 bin 等的数组中...

打开文件,逐行读取文件数据,然后从该行中提取所需的内容。

  std::string line;
  ifstream read;
  //open data files     
  read.open(file_name);
  if(read.is_open())
    cout << "File ./" << file_name << " is open.n";
  else {
    cout << "Error opening " << file_name << ".n";
    exit(0);
    }
    while (std::getline(read, line))
    {
    // line =3 A 0100 3 E 0101 3 G 0110 3 ...     
     std::istringstream iss (std::move(line));
     std::string val_str, al, bin; 
        while(! iss.str().empty())
        {
            try{
                iss>>val_str;               
                int val= std::stoi(val_str);     //val = 3 in the first run of the while loop
                iss >> al;               //al = A  in the first run of the while loop
                iss >> bin
                // you can use val, al ,bin
            }catch(..){
                break;
            }
        }
    }