2012-12-04 153 views
1

我帶屬性的文本文件中的數據集,其看起來是這樣的工作:如何從文件中讀取一行中的特定字符?

e,x,y,w,t,a,f,c,b,k,e,c,s,s,w,w,p,w,o,p,n,s,g 
e,f,y,y,t,l,f,c,b,w,e,r,s,y,w,w,p,w,o,p,n,y,p 
e,b,s,w,t,a,f,c,b,w,e,c,s,s,w,w,p,w,o,p,n,s,g 
e,b,s,w,t,a,f,c,b,w,e,c,s,s,w,w,p,w,o,p,k,s,m 
e,x,y,n,t,l,f,c,b,w,e,r,s,y,w,w,p,w,o,p,k,y,g 
e,b,s,w,t,a,f,c,b,k,e,c,s,s,w,w,p,w,o,p,k,s,g 
e,x,f,g,f,n,f,c,n,g,e,e,s,s,w,w,p,w,o,p,n,y,u 
e,b,s,y,t,l,f,c,b,k,e,c,s,s,w,w,p,w,o,p,n,s,g 

現在,我試圖找出如何我可以輕鬆地閱讀從給定列字符(比如,例如,每行的第5個字母)。我無法弄清楚如何做到這一點。有誰知道我可以做什麼?

+0

都能跟得上,只需逐行閱讀,然後選出你想要的角色。 – nhahtdh

+0

使用CSV閱讀器。 http://stackoverflow.com/questions/1120140/csv-parser-in-c – djechlin

回答

0

考慮設定你處理數據的只有一個字符,而不是一個任意大小的,你可以推斷出每個字符後跟一個逗號,所以

1個字符= 2個的文件空間計算所需的字符

如果你想讀5日線,這將是該文件中的(4*2 + 1)點。您可以將該行讀入字符串並在字符串中找到它,或者每次只從文件中取一個字符,直到達到所需的數字。

cout << "What column would you like to read from? "; 
cin >> num; 
int Length = (num - 1) * 2 + 1; 
char ColumnLetter; 
for(int i = 0; i < Length; i++) 
{ 
    inFile >> ColumnLetter; 
} 
0

如果在你的數據沒有空格,每個符號由逗號分隔,字符串的結束是一個符號「\ n」,你可以做這樣的事情:

#include <iostream> 
#include <fstream> 

using std::ifstream; 

ifstream file; 
const int LINE_WIDTH; //number of your chars in line (without commas) 

char GetFromFile(int row, int position) //row and position indexes start from 0! 
{ 
    file.seekg(row * (LINE_WIDTH * 2) + position * 2); 
    return file.get(); 
} 

int main() 
{ 
    file.open("data.txt", ios::binary); 

    char c = GetFromFile(10, 3); 

    file.close(); 
    return 0; 
} 
相關問題