2016-09-21 38 views
-2

我想按3行值讀取我的數組行。所以,當我恢復3個值把我的矩陣等等...按行讀取數組3行值3個值

for(int i=0; i<_height; i++) { 
    for(int j=0; j<_width; j++) { 
     result = ifile.get(); 
     (image)[i][j]= (int)result; 
     // Display the array which contains data 
     cout << (image)[i][j] << " "; 
    } 
    cout << endl; 
} 
+0

而你的問題其實是? –

+0

如果您的文件包含文本格式的值,則可能需要使用'ifile >>結果;'。 –

+0

我該如何做到這一點,通過3個值逐行檢索3個值? – Rayan958

回答

1

試試這個:

for (unsigned int row = 0; row < 3; ++row) 
{ 
    for (unsigned int column = 0; column < 3; ++column) 
    { 
     inFile >> image[row][column]; 
    } 
} 

因爲你的價值觀是由「白色空間」,這是空格,製表符或換行符分隔,無論所有值是在一行還是多行,這都應該起作用。

編輯1:上面的更安全的替代
假定總是有9個值和它們都是有效的整數。 如果出現錯誤,上述內容將無法使用。以下是更健壯的方法。

unsigned int row = 0; 
unsigned int column = 0; 
bool all_values_read = false; 
int value = 0; 
while ((inFile >> value) && !all_values_read) 
{ 
    image[row][column] = value; 
    ++column; 
    if (column >= 3) 
    { 
     column = 0; 
     ++row; 
     if (row >= 3) 
     { 
     all_values_read = true; 
     } 
    } 
} 
0

你可以像如下實現的東西:

int count = 0; 
for(int i=0; i<_height; i++) { 
    for(int j=0; j<_width; j = j +3) { 
     result = ifile.get(i,j); 
     (image)[i][count]= (int)result; 
     count += 1; 
     // Display the array which contains data 
     cout << (image)[i][count] << " "; 
    } 
    count = 0; 
    cout << endl; 
} 

get(int i, int j)功能是恢復三個值(或更少,如果行j+3前結束)從的位置j啓動功能i-th一排。

+0

當然,您還需要提供所有必要的檢查。附上的代碼只是一個想法! – acornagl

+0

不算++請嗎? – Rayan958

+0

隨意編輯;) – acornagl