2017-11-08 16 views
-1

私のプログラムは整理配列を表示する出力ファイルを作成していません。コードはエラーなしで実行されますが、ソースファイルを保持するフォルダをチェックすると、result.txtというファイルは表示されません。なぜどんなアイデア?C++プログラムが出力ファイルを作成していません。コンパイラはエラーを表示しません

#include <iostream> 
#include <fstream> 
#include <cstdlib> 
using namespace std; 
void sort(double a[], int control); 
int main() 
{ 
    int control=15; 
    double a[control]; 
    ifstream in_stream; 
    in_stream.open("data.txt"); 
    if(in_stream.fail()) 
    { 
    cout<<"Input file opening failed\n."; 
     exit(1); 
    } 
    for (int i=0;i<15;i++) 
    { 
     in_stream>>a[i]; 
    } 
    in_stream.close(); 

    sort(a,control); 

    ofstream out_stream; 
    out_stream.open("result.txt"); 
    if(out_stream.fail()) 
     { 
      cout<<"Output file opening failed\n."; 
      exit(1); 
     } 
    for(int i=0;i<15;i++) 
    { 
     out_stream<<a[i]; 
    } 
    out_stream.close(); 

    return 0; 
} 

void sort(double a[], int control) 
{ 
    int swapped=0,temp,i; 
    while(1) 
    { 
    for (i=0;i<control;i++) 
     { 
      int temp=a[i]; 
      a[i]=a[i+1]; 
      a[i+1]=temp; 
      swapped=1; 
     } 
     if (swapped == 0)break; 
    } 

} 
+0

多分それはあなたの入力ファイルを検索し、[* *可変長配列を](https://en.wikipedia.org/wiki/あなたが使用している – drescherjm

+0

「入力ファイルのオープンに失敗しました」印刷後に終了しませんでしたVariable-length_array)は、技術的にはC++の一部ではありません。 'control'をコンパイル時定数にしてください。単純なCスタイルの配列の代わりに[' std :: array'](http://en.cppreference.com/w/cpp/container/array)を使うことをお勧めします。 –

+1

あなたの問題の* one *については、 'sort'関数ではあなたは* [*未定義の動作*](http://en.cppreference.com/w/cpp/language)につながります。/ub)。あなたのロジックも*非常に欠陥があるようです。最後に、[あなたのプログラムをデバッグする方法を学ぶ](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)をお勧めします。 –

答えて

0

あなたのプログラムは、出力ストリームを書き留めている部分に到達することはありません。なぜなら、あなたのソートメソッド内で無限ループに陥ってしまうからです。

このバブルソート方法を使用できます。

// A function to implement bubble sort 
void sort(double a[], int control) { 
    int i, j; 
    for (i = 0; i < control - 1; i++) 

     // Last i elements are already in place 
     for (j = 0; j < control - i - 1; j++) 
      if (a[j] > a[j + 1]) { 
       int temp = a[i]; 
       a[i] = a[i + 1]; 
       a[i + 1] = temp; 
      } 
} 
関連する問題