从特定行读取C++中的文件,然后将其存储在Vectors/Array中

Read a file in C++ from a specific Line and then store it in Vectors/Array

本文关键字:存储 Array Vectors 然后 文件 读取 C++      更新时间:2023-10-16

我是C++编程的新手,我做了阅读文件的功课。我正在从这个cpp教程学习C++:基本文件io站点。

我有一个文件,其内容看起来像:

Input: /path/to/the/file/
Information :xxx
Type of File: Txt file
Extra Information Value = 4
Development = 55
NId      CommId
1        0
3        0
8        7
.   .
And so on...

该文件包含大约10000 Nodes及其相应的CommID。在该文件中,Node and CommIdTAb space分隔。我正在使用以下代码作为输入读取此文件:

ifstream commFile("CommTest.txt");
if (!commFile)
       {
         // Print an error and exit
    cerr << "Uh oh, CommunityTest File could not be opened for reading!" << endl;
                 exit(1);
             }
while(commFile)
{
    // read communityFile from the 6th Line
    string strLine;
    getline(commFile, strLine);
    cout << strLine << endl;
}

我有两个问题:

  1. 我想从第7行开始阅读,即10等等
  2. 我怎样才能从第7行开始读

我检查了很多问题,发现如果txt文件的行长度不同,就不可能跳到行号。

我想知道如何使用seekg,在到达7号线之前,我需要数比特。

Please let me know, how to do it?

我想在两个独立的整数中得到节点和CommId。一旦我有了Integer中的Node,我就想从Graph文件中搜索该Node的邻居节点(该文件也作为输入提供,它有边信息(。在获得该节点的Neighbours后,我想存储收集到的Neigbors及其CommId(每个节点的CommId都可以从上面的文件中获得(。我想将它们成对存储在Array/Vector中。

例如:

从此文件中读取1 0之后。我将选择节点1从图形文件中查找节点1的邻居。为每一个邻居对于节点1,我想将信息保存为一对。例如,如果节点1有两个邻居节点。即节点63和节点55。如果节点63属于commId 100,节点55属于commId 101应该是:

[(63100(,(55101(..]等等。

STackOverflow论坛的学习链接建议我使用Vectors、Map、STructs for Graphs。我以前从未使用过矢量/贴图、结构。我知道数组,因为我以前使用它。

请提出最好的方法。

提前谢谢。如有任何帮助,我们将不胜感激。

您可以通过以下方式从7行读取文本文件:

for (int lineno = 0; getline (myfile,line) && lineno < 7; lineno++)
  if (lineno > 6)
      cout << line << endl;

从#7行获取NId and CommId后,您可以在字符串流中获取它。你可以从字符串流中学习

std::stringstream ss;
ss << line;
int nId,CId;
ss >> nId >> CId;

然后可以拿2D阵列,我认为你必须处理2D阵列,如果

array[row][column]

每个row定义为NId,并对应于一行中的commId作为column值存储。

根据您的示例:[(63100(,(55101(..]等等。

Here NId 63, 55 .....
So you can..
array[63][0] = 100
array[55][0] = 101
so on....

您可以通过count来处理列值,如0,1,2….

  int main(int argc, char **argv) {
    vector<int> nodes;
    map<int, vector<int> > m;
    ifstream commFile("file.txt");
    string strLine, node_string;
    int node;
    if (!commFile.is_open()) {
        cerr << "Uh oh, CommunityTest File could not be opened for reading!" << endl;
        return -1;
    }
    // Ignore the first lines of your file, deal with the empty lines
    for(int i = 0; i < 12 && std::getline(commFile,strLine); i++) {
        cout << "Line to ignore = " << strLine << endl;
    }
    while(getline(commFile,strLine)) {
        istringstream split(strLine);
        // split the string with your nodes
        while(getline(split, node_string, ' ')) {
            std::istringstream buffer(node_string);
            buffer >> node;
            // push it into a temporary vector
            nodes.push_back(node);
        }
        if(nodes.size() >= 2) {
            // add into your map
            m[nodes[0]].push_back(nodes[1]);
        }
    }
    return 0;
}