如何将最后一个元素添加到包含 C++ 数组的结构的向量中

How to add the last element into a vector of a struct containing an array in c++

您好,我想将最后一个元素添加到包含数组的结构向量中。我试图将它添加到它的循环中,但常量字符有问题。它说“从‘const char*’到 char 的无效转换”[-fpermissive]

我的文件名为 myfile.txt.log

id  value 
1   ABC  
2   BDV  
3   COO  
4   DDC  
5   EEE  
6   FGE  
7   GTW  
8   HFE  
9   IOO  
10  KPP  

期望的输出:

vector size: 11 
vector content: ABC 
vector content: BDV 
vector content: COO 
vector content: DDC 
vector content: EEE 
vector content: FGE 
vector content: GTW 
vector content: HFE 
vector content: IOO 
vector content: KPP 
vector content: XXX 

这是我的代码。任何输入都会很棒!我在 C++ 98

#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

struct V {
  char a[10];
};

int main() {
   
  FILE * pFile;
  char mystring [100];
  int i;
  char str[3];
  char strCp[3];
  vector<V> input;
 
  pFile = fopen ("/uploads/myfile.txt.log" , "r");
  if (pFile == NULL) perror ("Error opening file");
  else {
    while ( fgets (mystring , 100 , pFile) != NULL )
    {
      sscanf(mystring, "%d %s", &i, str);
      strncpy(strCp, str, 3);
      //puts(strCp);
      
      V v;
      int size = sizeof(strCp)/sizeof(strCp[0]);
      for ( unsigned int a = 0; a < size; a++ )
      {
        v.a[a] = strCp[a];
        v.a[a-1] = "XXX";
      }
      
      // Set vector
      input.push_back(v);

    }
    
    //Vector Output
    cout << "vector size: " << input.size() << endl;
    vector<V>::iterator it;
    for ( it = input.begin(); it != input.end(); it++ )
    {
      cout << "vector content: " << it->a << endl;
    }

    fclose (pFile);
   }
   
   return 0;
}

   

考虑使用比 C 更多的 C++ 语义:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

struct V {
    char a[10];
};

int main()
{
    std::vector<V> input;
    std::string s;
    int count = 0;
    while (std::cin >> s)
    {
        count++;
        if ((count % 2) == 0)
        {
            V v = {};
            strncpy(v.a, s.c_str(), 4);
            input.push_back(v);
        }
    }

    V endV = {};
    strncpy(endV.a, "XXX", 4);
    input.push_back(endV);

    fstream logfile;
    logfile.open("logfile.txt", std::ios_base::out);
    if (logfile.is_open())
    {
        for (size_t i = 0; i < input.size(); i++)
        {
            logfile << input[i].a << "\n";
        }
        logfile.close();
    }

    return 0;

}