如何从字符串的每一行开头都有数字的文件中读取并将数字提取为 idx,然后将其存储在向量中。使用 C++

How to read from a file that has numbers in the beginning of each line of the string and extract numbers as an idx then store in a vector. Using C++

您好,我正在做一个学校项目,我正在尝试从包含以下内容的文件中读取:

the idx of question, the corresponding concept 
1 Arrays Hold Multiple Values
1 Pointer Variables
2 Arrays as Function Arguments
3 Comparing Pointers
4 Pointer Variables
5 Pointer Variables
6 Initializing Pointers
7 Pointers as Function Parameters
8 Arrays as Function Arguments
8 Pointer Variables
9 Arrays Hold Multiple Values
10 Pointer Variables

目标是将字符串开头的数字存储到向量容器中,以将其值与字符串的其余部分一起保存为相应的概念。

注意:每个数字代表测验中的一个问题,它可能包含多个概念,这些概念在文件中以不同的行分隔。因此,将这两个内容映射到一个具有相同数字 1 的字符串中是完全可以的。

我尝试了 2d 向量和 1d 向量,但我的问题是我不知道如何拆分字符串并检测开头的整数以及两位或三位整数问题会更复杂。

如有任何帮助,我们将不胜感激!!!!

这是我试过的:

void MapQC::setMapQC()
{
    string line;
    string idxString;
    fstream inFile;

    int numOfLines = 0;
    int idx;

    inFile.open("database/map-question-concept.txt", ios::in);

    if (inFile.is_open())
    {
        while (!inFile.eof())
        {
            getline(inFile, line);

            vector<string> row;

            for (int i = 0; i <= numOfLines; i++)
            {
                if (getline(inFile, line, ' '))
                {
                  // cout << line << endl;
                  row.push_back(line);
                }
            }
            mapQCVec.push_back(row);
            numOfLines ++;
            cout <<"row at: " << row[1] << endl;
        }

    }

    inFile.close();
}

这不是最干净的解决方案,但它应该可以帮助您入门。下面将每行开头的数字与其他内容分开:

// for each line string
string idxStr;
string lineWithoutIdx;
for (const char& c : line) 
{
    if (isdigit(c)) { idxStr.push_back(c); }
    else { lineWithoutIdx.push_back(c); }
}
const int idx = atoi(idxStr.c_str()); // numbers-string to int
// use containers of your choice, e.g. std::vector
lineIndices.push_back(idx);
lineContents.push_back(lineWithoutIdx);

每一行在每个容器中都有自己的条目,然后您可以 filter/merge 重复,或通过 lineIndices 中的数字访问 lineContents 中的特定字符串。请注意,这不会检查数字是否在文本中,而是假设它们位于每行的开头,如您的示例所示。