2017-05-04 47 views
0

我不擅長編碼,我想問一個關於我的代碼的問題。我想要的是翻轉文件中寫入的數字。翻轉號碼,C++代碼

123一樣,它會推出321

我已經寫了代碼,我找不出什麼不對的地方,我希望你會需要一些時間,並通過它看,我失去了一些東西。 ..

#include <iostream> 
#include <fstream> 


using namespace std; 


int main() 
{ 

    char duomenys[] = "2017kuzU1.txt"; 

    int n; 
    int pradinis[] = {}; 
    int check; 
    int skaitmenys[] = {}; 


    ifstream fd(duomenys); 
    fd >> n; 


    for(int P = 0; P < n;P++) 
    { 
     check = 0; 
     fd >> pradinis[P]; 
     while(pradinis[P] > 0){ 
      skaitmenys[check] = (pradinis[P]%10); 
      pradinis[P] /= 10; 
      check++; 
     } 

     for(int j = 0; j < check;j++){ 
      cout << skaitmenys[j] << endl; 
     } 
    } 

return 0; 
} 
+4

聽起來您可能需要了解如何使用調試器來逐步執行代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。深入閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver

+0

也許將整數翻轉成單獨的函數只接收一個int。我認爲這會讓你更明白你的功能有什麼問題。 – didiz

+0

除了關於調試的註釋之外,通常還要熟悉標準庫。許多問題可以通過讓專家爲你發明輪子來解決。 即便如此,以下可能會有一些用處:http://en.cppreference.com/w/cpp/algorithm/reverse –

回答

0

有這麼多你的代碼錯誤,真的是無處下手,除了OVER。

// by Dt t 5/4/2017 
// this code will repeatedly write to a file then reverse what it wrote. Go 
//look in the file before and after runs to see the effect... 
//create 

#include "stdafx.h" 
#include <iostream> 
#include <fstream> 
using namespace std; 


int main() 
{ 
const int SIZE = 5; 
ifstream fin; 
ofstream fout; 
char character; 
char myChars[SIZE]; 

fout.open("2017kuzU1.txt");//creates and then fills the file 
fout<<'X'<<'b'<<'c'<<'1'<<'2'; 
fout.close();//close the file 

fin.open("2017kuzU1.txt");//opens and reads the file 

for(int i = 0; i<SIZE;i++) 
{ 

    fin.get(character);//now look at the file to be sure the stuff is there 
    cout<<character; 
    myChars[i] = character;//write it into an array for later 
} 
cout<<" \n"; 

fin.close();//close the file 
for(int i = 0; i<SIZE;i++) 
{  
    cout<<(myChars[i]); 
} 
cout<<"GTF"; 
system("pause"); 
fout.open("2017kuzU1.txt");//open the file for output 
for(int i = 0; i<SIZE;i++) 
{ 
    fout<<(myChars[4-i]);//reverse the contents fo the file 
    cout<<(myChars[4-i]);//show the reverse on the screen 
} 
fout.close(); 
return 0; 
} 

此代碼將在項目文件夾中創建一個文件,將一些東西寫入文件然後關閉它。那麼它將打開文件並以相反的順序將文件寫回文件。在運行之前查看文件,然後在運行之後查看效果。請注意,這些值在每次運行開始時重置...