如何向阵列添加多个字符串或用户输入?我正在尝试创建一个联系簿,要求用户最多添加10个联系人。我试图将它们存储为数组或txt文件,然后我希望能够使用此输入。
这是我的代码。如果我想说的不清楚,运行代码会有所帮助。
#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;
}
答案 0 :(得分:2)
你可能最好使用一组结构而不是两个单独的数组来存储名称&amp;每个条目的年龄。然后你可以循环使用strcpy将输入字符串从name复制到struct的名称中。如果你对结构感到不舒服,你也可以使用几个二维数组。
这看起来像是一个家庭作业,所以我不打算发布代码,但是一个基本的算法让你开始(并希望简化你所拥有的):
#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的工作原理是它查看它传递的第一个字符并转换所有数字,直到它遇到数组中的非数字字符。因此,如果你有char数组c =“123h”atoi将返回123.如果你传递atoi“1h2”它将返回1.
此外,您可以使用fprintf将char数组和int打印到文件中。
所以,如果你有int i和char s [10] =“hello”和文件流,你可以像以下一样打印流:
fprintf(stream,“我要显示的文字:%s%i”,s,i)
我希望有所帮助。