如何获取输入文件一行的第二个和最后一个字符并在 C++ 中组成数组?

How can I get the second and last characters of a line for an input file and compose array in C++?

我有一个 input.txt 文件,我想逐行读取输入文件,我想组成 2 个数组。 space 之后的第一行给出了数组的大小。对于下面的示例输入文件,数组的大小为 3。从第一个 space 之后的第二行到文件末尾组成数组 A[]。对于此示例,A[3]={5,8,14} 从第二行 space 之后的第二行到输入文件的末尾组成数组 B[] 的内容。对于此输入文件,它是 B[3]={67,46,23}。在第一行之后每一行的第一个数字只是给出每个 line.Input 文件的行号是这样的:

10 3
1 5 67
2 8 46
3 14 23

下面是我的起始代码。如何获取输入文件一行的第二个和最后一个字符?

#include<stdio.h> 
#define N 128
#include <iostream>
#include <fstream>

int A[N];
int B[N];

int main(){

    ifstream fin;
    fin.open("input.txt", ios::in);

    char CHARACTER;
    int ITEMNUMBER = 0;

    while (!fin.eof() ) {

    fin.get(CHARACTER);
        if (CHARACTER== '\n'){
            ++ITEMNUMBER;
        }       

    }
    printf("\n");
    cout << "NUMBER OF ITEMS: " << ITEMNUMBER<< endl; 

return 0;
}

如果文件与您上面给出的格式保持一致并且您没有达到数组的限制,我认为这将解决您的问题。

int main(int argc, const char * argv[])
{
  ifstream fin("input.txt", ios::in);

  int A[N];
  int B[N];

  //get first num and size
  int first; // not sure what that is for but i guess you know
  int arraySize;

  fin >> first;
  fin >> arraySize;


  int id;
  int aData;
  int bData;
  int i = 0;

  while(fin >> id >> aData >> bData)
  {

    A[i] = aData;
    B[i] = bData;
    i++;
  }  


  return 0;
}

您真的需要 C 风格数组的解决方案吗?

或者使用标准容器的解决方案适合您?

在第二种情况下(我建议)我提出以下示例

---修改为加载打印firstNum---

#include <vector>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <stdexcept>

int main ()
 {
   std::ifstream fin("input.txt", std::ios::in);

   int      firstNum;
   int      unused;
   unsigned dimV;

   if ( ! (fin >> firstNum >> dimV) )
      throw std::runtime_error("error reading dimension");

   std::vector<int> a(dimV);
   std::vector<int> b(dimV);

   std::cout << "firstNum is " << firstNum << std::endl;

   for ( unsigned i = 0U ; i < dimV ; ++i )
      if ( ! (fin >> unused >> a[i] >> b[i]) )
         throw std::runtime_error("error reading dimension");

   for ( unsigned i = 0U ; i < dimV ; ++i )
      std::cout << "-- " << a[i] << ", " << b[i] << std::endl;

  return EXIT_SUCCESS;
}

输出

firstNum is 10
-- 5, 67
-- 8, 46
-- 14, 23