0

txtファイルを介して機能するプログラムをc ++で作成しようとしています。このファイルの数字に重複がある場合は、それらを印刷せず、一度表示される数字のみを印刷してください。

これは私が持っているコードです。しかし、ファイルを印刷してから、重複を探す代わりに2行目を再度印刷します...

どこが間違っているのか誰か教えてください。C ++にはかなり慣れていない

// array.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
    int array[100]; // creates array to hold numbers
    short loop=0; //short for loop for input
    string line; //this will contain the data read from the file
    ifstream myfile ("problem3.txt"); //opening the file.
    if (myfile.is_open()) //if the file is open
    {
        while (! myfile.eof() ) //while the end of file is NOT reached
        {
            getline (myfile,line); //get one line from the file
            array[loop] = line;
            cout << array[loop] << endl; //and output it
            loop++;
        }

        for (int i = 1; i < loop; i++)
        {
            bool matching = false;
            for (int j = 0; (j < i)&& (matching == false); j++)
            {
                 if (array[i] == array[j]) 
                      matching = true;
             }
             if (!matching) 
                cout<< array[i] << " "
        }   
        myfile.close(); //closing the file
     }
      else 
         cout << "Unable to open file"; //if the file is not open output
     system("PAUSE");
     return 0;
 }
4

2 に答える 2

1

少なくとも 1 つのエラー:arrayは整数の配列として宣言されています。文字列lineを読み取って、すぐ下に割り当てstringintいます:

 getline (myfile,line); //^^line is string, array[i] is int
 array[loop] = line;

これらの行をベクトルで読み取ってから std::unique を呼び出して、ベクトルを一意にして出力することができます。行は必ずしも整数の行であるとは限らないため、整数配列に格納すると機能しない場合があります。

あなたは試すことができます:

#include <vector>
#include <string>
#include <algorithm>
#include <iterator> 

int main()
{
    std::vector<std::string> data;
    ifstream myfile ("problem3.txt");
    string line;
    //if not required to use array
    while (getline(myfile, line))
    {
      data.push_back(line);
    }

    std::vector<std::string> data(dataArray, dataArray + 100);

    myfile.close();
    std::sort( data.begin(), data.end() );
    data.erase( std::unique( data.begin(), data.end()), data.end() );
    //now print vector out:
    std::copy(data.begin(), data.end(), ostream_iterator<string>(cout, " \n"));
    return 0;
}
于 2013-04-24T02:38:36.570 に答える
0

ネストされた for ループを使用する代わりに、配列を使用して、特定の整数が表示される回数をカウントすることをお勧めします。その後、それを1回ループして、カウントが1の整数のみを出力できます。

ネストされた for ループの問題の 1 つは、 の範囲内で重複をチェックするだけでj < iあるため、配列の後半に重複がある場合でも整数を出力する可能性があることです。配列全体をチェックして、重複がないことを確認するだけです。

それでも試してみたい場合は、おそらく次のようなことをしたいと思うでしょう:

for (int i = 0; i < loop; i++) // start at 0!
{
   bool matching = false;
   for (int j=0; j<loop; j++) { // check the whole array for duplicates!
       if (i != j && array[i] == array[j]) {
           matching = true;
           break; // instead of complicated condition in for loop
       }
   }
   if (!matching) cout << array[i] << " ";
}  
于 2013-04-24T02:53:21.480 に答える