-1

私が実際に正しい方向に進んでいるかどうか知りたいのですが、私は現在 C++ 言語を学んでおり、Alex Alllain による Jumping into C++ と呼ばれるこの本を読んでおり、構造に関する章の最後に練習問題があります。連絡帳プログラムは、ユーザーが 1 つの構造に入力できるだけでなく、それぞれ別の名前と電話番号を持つ新しいエントリを追加できる必要があります。ユーザーが必要なだけエントリを追加できるようにします。これは簡単ですか? すべてまたは一部のエントリを表示する機能を追加して、ユーザーがエントリのリストを参照できるようにします。

以下は私が行ったことです。ソースコードが実際に正しいかどうか、構造と全体的な c++ についての私の理解を示しているかどうかを知りたいですか?

#include "stdafx.h"
#include "iostream"
#include "string"

using namespace std;

struct user{
    string name;
    int phone_num;
};


int _tmain(int argc, _TCHAR* argv[])
{
    int input, number;                      // will hold the users input at the beginning of the program
    int counter = 0;                // keep track of the array position
    int const arraySize = 10;       // size of the array
    user new_username[arraySize]; // will hold the users details    
    string name;                    // will hold the users input for the name

    cout << "CONTACTS\n";
    do{     


        cout << "+ADD [1] -EXIT[0]";
        cin >> input;


        if(input == 1){

                //cout << counter;
                cout << "\nName: ";
                cin >> name;
                new_username[counter].name += name;
                cout << endl << "\nPhone: ";
                cin >> number;
                new_username[counter].phone_num =  number;
                counter++;
            //set_user(counter);            

        }
        cout << "Name    Number\n";
        cout << "--------------\n";
        for(int j=0; j < arraySize; j++){

                cout << new_username[j].name;
                cout << " -- ";
                cout << new_username[j].phone_num;
                cout << "\n";
        } 

        cout << "\n";

    }while(input != 0);


    cout << "\n";
    system("PAUSE");
    return 0;
}
4

3 に答える 3

2

Stackoverflow はコード レビューに使用するためのものではありませんが、これには別のサイトがあります (まだベータ版ですが): https://codereview.stackexchange.com/

私が気づいたいくつかの簡単なこと:

  • プログラムは無効な入力を無視します (1 または 0 の代わりに 2、3 またはその他の数値を入力します)。
  • user配列がいっぱいかどうかを確認しません。
  • これは実際にはオブジェクト指向ではありません。

基本的な理解については... はい、そう思いますが、実際に始めるのは難しくありません。

「ユーザーが必要な数のエントリを追加できるようにする」を実現するには、動的配列を使用するか (追加するエントリの数をユーザーに尋ねる)、動的ストレージ (リンクされたリストなど) を使用する必要があります。

于 2013-01-03T01:00:11.253 に答える
0

ユーザーが必要な数の連絡先を追加できるようにする場合は、強力な標準テンプレート メカニズムを使用できます。

このアプリケーションについては、どちらかを見ることをお勧めします

std::vector

また

std::map

これはあなたがそれらをどのように使用するかです: (これは疑似コードであり、コンパイルされないことに注意してください)

#include <vector>

typedef struct {
   std::string name;
   double phoneNumber;
} YourStruct;

int main( int argc, char **argv ) {

std::vector<YourStruct> structVector;

do {
    int input;
    std::cin >> input;
    if (input) {
       //(read user input for name and number) 
       YourStruct yourStruct;
       yourStruct.name = (user input)
       yourStruct.phoneNumber = (user input)
       // insert into the vector
       structVector.push_back(yourStruct)
    }
} while (input != 0)

// now to print what you have:
for (int i = 0; i < structVector.size(); i++) {
    std::cout << structVector[i].name << ", " << structVector[i].number << std::endl;
}
}

ベクトルを使用する利点は、カウンター アイテムを使用しなくても、自動的にサイズが変更され、その大きさが追跡されることです。

さて、もう少しトリッキーなことをします。マップを使用して、「キー」値を使用して名前を取得します。次のコードはコンパイルされませんが、機能的にはタスクを実行する方法です。

#include <map>

int main(int argc, char** argv) {
    std::map<std::string,double> myMap;
    // the string is the "key" value, which can be the name of the person
    // while the "independent" is the phone number
    do {
       // determine if the user wants to put another entry in the map
       if (insert) {
          std::string name = (user input name)
          double number = (user input number)
          myMap[name] = number;
       }
    } while (input != 0)

    // now we can iterate through the map
    std::map<std::string,double>::iterator it;
    for (it = myMap.begin(); it != myMap.end(); ++it) {
       std::cout << it.first << ", " << it.second << std::endl; 
    }

    // also, you can look up by name
    it = myMap.find("Tony Stark");
    if (it != myMap.end()) { // if this condition is met, it means you found one
       std::cout << it.first << ", " << it.second << std::endl; 
    }
}

全体として、コードは適切に見えます。ただし、C++ ではありません。あなたは C プログラマーのようにプログラミングしています。C++ の優れている点は (もちろん polymophisim を除いて)、強力なテンプレート ライブラリです。

テンプレートでできることを少しだけ紹介しました。気になる点などありましたらコメントください。私たちは皆、あなたがいる場所にいました。本から独学したことを称賛します.

于 2013-01-03T01:18:06.980 に答える
0

あなたの質問とコードから、あなたは新しいプログラマーのように思えます。そのため、答えを説明し、コードに関するメモをいくつか示します。

「アイテムの数だけ」の問題を解決するには、いくつかのアプローチがあります。最も簡単で、おそらくかなり良い解決策は、mapを使用することです。どの言語でも、名前が異なります。しかし、通常、名前は辞書、連想配列です...

マップを使用すると、次のことに対処できます。

  • アイテム数
  • 名前順にソート
  • フィルタリングが簡単になります。それは、何をしたいか、およびフィルターがどれほど洗練されているかによって異なります。

私が話した他のアプローチは、はるかに基本的で、より多くのコードで構成されていますが、マップオブジェクトを自分で実装する方法の感覚を与えてくれますが、これは別の問題です。

上記のリンクでは、電話入力の例を示しています。ただし、引き続き構造体を使用する場合は、キーを名前として、値を構造体自体にすることができます。その理由の 1 つは、後で住所と会社名を追加する予定がある場合です。

コードに関するいくつかのメモ。

    #include "stdafx.h"
 #include "iostream"
#include "string"

using namespace std;

//use meanigful name, instead of user it can be phoneEntry
struct user{
    string name;
//Starting using the following conventions using the capital letter in variable names for example phoneNumber

//int は電話番号の神ではありません。スターやハッシュ、または先頭のゼロ、プラス記号が必要になる場合があるためです。タットにも紐を使ったほうがいいです。もちろん、ユーザー入力を取得するたびに、int phone_num; を検証する必要があります。};

//Why the name of the function is not main, why its _tmain
int _tmain(int argc, _TCHAR* argv[])
{
//Keep going with your comments, with time you would imbrase your own style based on things that you will see. But in general commenting is very important
//Give meanigful name, instead input userCommand for example
    int input, number;                      // will hold the users input at the beginning of the program
    int counter = 0;                // keep track of the array position
    int const arraySize = 10;       // size of the array
//Again meangful names
    user new_username[arraySize]; // will hold the users details    
    string name;                    // will hold the users input for the name

    cout << "CONTACTS\n";
    do{     


        cout << "+ADD [1] -EXIT[0]";
        cin >> input;


        if(input == 1){

                //cout << counter;
                cout << "\nName: ";
                cin >> name;
                new_username[counter].name += name;
                cout << endl << "\nPhone: ";
                cin >> number;
                new_username[counter].phone_num =  number;
                counter++;
            //set_user(counter);            

        }
        cout << "Name    Number\n";
        cout << "--------------\n";
        for(int j=0; j < arraySize; j++){

                cout << new_username[j].name;
                cout << " -- ";
                cout << new_username[j].phone_num;
                cout << "\n";
        } 

        cout << "\n";

    }while(input != 0);


    cout << "\n";
    system("PAUSE");
    return 0;
}

お役に立てば幸いです

于 2013-01-03T01:20:41.380 に答える