2017-03-06 93 views
0

我正在研究一個小項目來練習C++中的I/O文件,但我無法弄清楚這個問題。我想編寫和算法,在文本文件中按字母順序重新排列單詞(最好是氣泡排序)。這是我到目前爲止如何從文本文件寫入數組和從數組寫入文本文件?

ifstream file("lab01.txt"); 
ofstream fileOut("lab01_out.txt"); 
char s[20][10];//variable for copying the words 

//check if file was oppened 
if (!file.is_open()) { 
    cout << "Error, file was not oppened!" << endl; 
    return -1; 
} 

//copy words from file to 2d array 
for (int i = 0; i < 20; i++) 
    file >> s[i]; 


char check[1]; 

//bubble sort 
for (int i = 0; i < 19; i++) { 
    for (int j = 0; j < 18 - i; j++) { 
     if (strcmp(s[j], s[j + 1]) > 0) { 
      strncpy_s(check, s[j], _TRUNCATE);//if not truncated error "buffer to small" 
      strncpy_s(s[j], s[j + 1], _TRUNCATE); 
      strncpy_s(s[j + 1], check, _TRUNCATE); 
     } 
    } 
} 

//printing array to output file and to console. 
for (int i = 0; i < 20; i++) { 
    cout << s[i] << endl; 
    fileOut << s[i] << endl; 
} 

//closing files. 
file.close(); 
fileOut.close(); 

問題是,這是我的輸出文件的樣子。我得到這些符號而不是字... enter image description here

任何幫助將不勝感激!

+1

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

+0

***我正在一個小項目來練習C++中的I/O文件***如果你真的這樣做,我的建議是退出使用char數組而不是std :: string。 – drescherjm

+0

對於初學者,我會將'char check [1];'更改爲'char check [10];'。 –

回答

1

一些提示如何在Modern C++中編程。

  • 不要把整個STD命名空間到你的代碼 - Why is 「using namespace std」 considered bad practice?
  • 代替了傳統陣列的使用一個std ::向量;
  • 不要評論明顯的例如。 !file.is_open() 這可能會導致代碼被修改後的陳舊評論,並且評論不會​​被修改。使代碼顯而易見。
  • 不需要關閉該文件在程序塊結束(析構函數會爲你)
  • 使用可用的標準算法(如化std :: swap)
  • 使用有意義的變量名

-

#include <iostream> 
#include <fstream> 
#include <string> 
#include <vector> 
#include <algorithm> // until c++11 
#include <utility> // since c++11 

using std::cout; 
using std::endl; 
using std::string; 

int main() 
{ 
    std::ifstream fileToRead("lab01.txt"); 
    std::ofstream fileOut("lab01_out.txt"); 

    if (!fileToRead.is_open() || !fileOut.is_open()) 
    { 
     cout << "Error, file was not oppened!" << endl; 
     return -1; 
    } 

    std::vector<string> strings; 
    string readString; 

    while (fileToRead >> readString) 
    { 
     strings.push_back(readString); 
    } 

    const auto stringsCount = strings.size(); 
    // bubble sort 
    for (auto lastPosition = stringsCount - 1; lastPosition > 0; lastPosition--) 
    { 
     for (std::size_t checkedPosition = 0; checkedPosition < lastPosition; checkedPosition++) 
     { 
      if (strings[ checkedPosition ] > strings[ checkedPosition + 1 ]) 
      { 
       std::swap(strings[ checkedPosition ], strings[ checkedPosition + 1 ]); 
      } 
     } 
    } 

    for (string str : strings) 
    { 
     cout << str << endl; 
     fileOut << str << endl; 
    } 
} 
+0

謝謝@Robb,指出 – sziko