Как добавить более одного пользовательского ввода в массив? - PullRequest
0 голосов
/ 22 октября 2011

Как я могу добавить более одной строки или пользовательский ввод в массив?Я пытаюсь создать книгу контактов, которая требует от пользователя добавить до 10 контактов.Я пытаюсь сохранить их в виде массива или текстового файла, а затем я хочу использовать этот ввод.

Вот мой код.Если то, что я пытаюсь сказать, не понятно, выполнение кода поможет.

#include <cstdlib>
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
    // declare two variables;
    char name[20];
    int age;
string ans;
do {    
    // get user to input these;
    cout << "What is your name: ";
    cin >> name;
    cout << "What is your age : ";
    cin >> age;
    cout<<"continue ";cin>>ans;
  }while((ans == "y" || ans=="yes"));  
    // create output stream object for new file and call it fout
    // use this to output data to the file "test.txt"
    char filename[] = "test.txt";
    ofstream fout(filename);
    fout << name << "," << age << "\n";    // name, age to file
    fout.close();   // close file

    // output name and age : as originally entered
    cout << "\n--------------------------------------------------------"
         << "\n name and age data as entered";
    cout << "\n    Your name is: " << name;
    cout << "\n    and your age is: " << age;     

    // output name and age : as taken from file           

    // first display the header
    cout << "\n--------------------------------------------------------"
         << "\n name and age data from file"
         << "\n--------------------------------------------------------";   

      ifstream fin(filename);

       char line[50];               
    fin.getline(line, 50);      


    char fname[20];     
    int count = 0;       
    do
    {
        fname[count] = line[count];       
        count++;
    }
    while (line[count] != ',');        
    fname[count] = '\0';              


    count++;
    char fage_ch[10];    
    int fage_count = 0;   
    do
    {
        fage_ch[fage_count] = line[count];   
        fage_count++; count++;               
    }
    while (line[count] != '\0');             
    fage_ch[fage_count] = '\0';


    int fage_int = 0;        
    int total = 0;           
    char temp;               

    for (int i = 0; i < (fage_count); i++)
    {
        temp = fage_ch[i];
        total = 10*total + atoi(&temp);
    }

    fage_int = total;

    // display data
    cout << "\n\n    Your name is: " << fname;
    cout << "\n    and your age is: " << fage_int;
    cout << "\n\n--------------------------------------------------------";    

      cout <<endl;

    return EXIT_SUCCESS;
}

1 Ответ

2 голосов
/ 22 октября 2011

Возможно, было бы лучше использовать массив структур вместо двух отдельных массивов для хранения имени и возраста для каждой записи. Затем вы можете просто перебрать strcpy, чтобы скопировать входную строку из name в имя вашей структуры. Если вам неудобны структуры, вы также можете использовать пару двумерных массивов.

Это похоже на домашнее задание, поэтому я не собираюсь публиковать код, но для базового алгоритма, который поможет вам начать (и, надеюсь, упростить то, что у вас есть):

#define MAX_CONTACTS 10
#define MAX_NAME_LENGTH 20

// 2D array to store up to 10 names of max 20 character length
char nameVar[MAX_CONTACTS][MAX_NAME_LENGTH]
int ageVar[MAX_CONTACTS]

do until end of user input
    read name into nameVar[index]
    read age into ageVar[index]
    index += 1
end loop

while contactCounter < index
    ouput nameVar[contactCounter]
    output age[contactCounter]
    // you could also write to file in this loop if thats what you're trying to do
    // using the fprintf function to write to an opened file
    contactCounter += 1
end loop

Кроме того, я не уверен, что вы пытаетесь сделать с этим вызовом atoi, но, похоже, в этом нет необходимости. Принцип работы atoi заключается в том, что он смотрит на первый передаваемый символ и преобразует все цифры, пока не встретит нецифровый символ в массиве. Поэтому, если у вас есть массив символов c = "123h", atoi вернет 123. Если вы передадите atoi "1h2", он вернет 1.

Также вы можете использовать fprintf для распечатки массива char и int в файл.

Так что, если у вас есть int i и char s [10] = "hello" и файловый поток, вы можете распечатать его как:

fprintf (поток, "мой текст для отображения:% s% i", s, i)

Надеюсь, это поможет.

...