2015-08-14 76 views
-2

我是C++编程的新手,我为阅读文件做了功课。我正在从这个cpp-tutorial: Basic-file-io网站学习C++。从特定行读取C++文件,然后将其存储在Vectors/Array中

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

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及其相应的CommIDNode and CommId在此文件中由TAb 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号线读即1 0等。
  2. 如何从7行开始阅读?

我查了很多问题,遇到了,这是不可能的跳转到的行号,如果txt文件的线路长度不同。

我不知道如何使用seekg中,我需要数位之前,我可以达到7号线

Please let me know, how to do it? 

我想在两个不同的整数节点和CommId。只要我有一个Integer中的Node,我想从Graph文件中搜索这个节点的邻居节点(这个文件也作为输入提供,并且它有边缘信息)。得到这个节点的邻居之后,我想存储收集到的邻居和它们的CommId(每个节点的commid可以从上面的文件中获得)。我想将它们作为一对存储在Array/Vector中。

例如:

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

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

学习链接,STackOverflow论坛建议我使用矢量,地图,图表的结构。在我的生活中,我还没有使用Vector/Maps,Structs。我知道Array是我之前使用过的。

请建议什么是最好的方法。

在此先感谢。每一个帮助将不胜感激。

+1

你把循环计数器和跳过处理行读,直到计数器达到7? –

回答

1

你可以通过这个阅读7无行文本文件:

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

从7号线越来越NId and CommId后,你可以把它在字符串流。您可以从stringstream

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

然后可以采取二维数组,我认为你必须处理二维数组,如果

array[row][column] 

row定义为NId和连续对应你和存储commId为一个column值。

根据你的例子:[(63,100),(55,101)..]等等。

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

您可以通过像0,1,2一个count和处理列值做.....

+0

哇。这是一个快速的回应。非常感谢答复和建议。如果我遇到了一些问题,我会尝试建议的方法并回来处理。再次感谢:) –

1
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; 
} 
相关问题