私はまだC++やコーディングと一般的な面でかなり新しいです。ファイルを読み込んで4行ごとに構造体の変数に保存する方法
最近私のコンピューターサイエンスクラスでは、名前、住所、電話番号、電子メールなど、さまざまな連絡先の情報を保存できる電話帳として機能するプログラムを作成するように求められました。
名前
住所
電話番号
メール
名2
住所2
:電話帳は次のように整理されるだろう
電話番号2
メール
2ですから、どの情報を保持するラインを予測、および構造体のベクトルにそれを保持することができるだろう。
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
struct Contact {
string name;
string address;
string phone;
string email;
};
string line;
vector<Contact> contacts;
int main(){
ifstream phonebook;
phonebook.open("phonebook.txt");
if (phonebook.is_open()){
int counter = 0;
int contactCounter = 0;
while(getline(phonebook,line)){
//cout << "line is " << line;
if(line.length()<=0){
cout << "In the if";
}else{
if(counter % 4 == 0){
contacts[contactCounter].name = line;
cout << counter;
}else if(counter % 4 == 1){
contacts[contactCounter].address = line;
}else if(counter % 4 == 2){
contacts[contactCounter].phone = line;
}else if(counter % 4 == 3){
contacts[contactCounter].email = line;
contactCounter++;
}
}
counter++;
}
} else cout << "an error has occurred in opening the contact list";
cout << "Address of contacts[0]: " << contacts[0].address; //a test to see if it worked
return 0;
}
(私もそれをテストするためにあらかじめ用意されたテキストファイルを持っている) しかし、私はプログラムを実行するたびにそれが出て失速し、その後終了します。私のコードは次のようなです。どんな情報?申し訳ありませんが、私は自分の思考プロセスをうまく説明できません。
あなたはあなたがそのレコードの完全な読書をしていることを知ったら、あなたは一つの '連絡先連絡先;'、次に 'contacts.push_back(連絡先)'を読み込むべきです。今はベクトルを範囲外に索引付けすることでUBを呼び出しています。言い換えれば: 'contacts [contactCounter]'は、このコードには現れないはずです*。 – WhozCraig