看板 C_and_CPP 關於我們 聯絡資訊
檔案可順利讀取了 但 想問的是 如何在 讀檔後 可以知道 總共有幾個數寫入矩陣 也就是下面的 n值 如何修改寫法 @@ #include <fstream> // 載入fstream標頭檔 #include <iostream> #include <cstdlib> using namespace std; int main(void) { float A[8]; int n; float tmp; ifstream ifile("test1.txt",ios::in); if(ifile.is_open()) { for(int i=0;i<8;i++) { ifile >> A[i]; } } else cout << "檔案開啟失敗..." << endl; n=sizeof(A)/sizeof(A[0]); cout<<"個數:"<<n<<endl; cout<<"排序前:"<<endl; for(int i=0;i<8;i++){ cout<<A[i]<<endl; } cout<<"排序後:"<<endl; for(int i=0;i<n-1;i++){ for(int j=0;j<n-1-i;j++){ if(A[j]>A[j+1]){ tmp=A[j]; A[j]=A[j+1]; A[j+1]=tmp; } } } for(int i=0;i<n;i++){ cout<<"A["<<i<<"]="<<A[i]<<endl; } cout<<"最大值:"<<A[n-1]<<endl; cout<<"最小值:"<<A[0]<<endl; ifile.close(); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 218.32.117.144 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1553000876.A.5F1.html
zamperla: 你可以在ifile >> A[i] 的那個迴圈內寫個sum計算有讀入 03/20 00:11
zamperla: 幾次 03/20 00:11
sarafciel: google std::vector 03/20 01:15
sarafciel: 把你的迴圈條件改EOF 然後把你讀到的東西都丟進vector 03/20 01:17
sarafciel: 再去call size()出來就有數量了 03/20 01:18
loveme00835: range style https://bit.ly/2Jn6lp7 不用謝 03/20 04:00
loveme00835: 你確定不去好好讀完書才來寫嗎? 看起來不是一兩章就 03/20 04:01
loveme00835: 能涵蓋的東西 03/20 04:01
tyjh: 感謝 因為想先確定這方法可不可行 03/20 10:15
tyjh: 才急著問 03/20 10:15
loveme00835: 那你知道檔案裡數字數目不定的時候,該怎麼辦嗎? 03/20 14:25
loveme00835: 拿掉讀檔, 用 cin 你會不會做? 這明顯不是方向問題 03/20 14:42
tyjh: 樓上請稍指點下囉 03/20 15:02
jxzhe: 好像可以在讀之前用seekg找end 就知道大小了 03/20 23:13