gpt4 book ai didi

C++ 拉取信息并循环显示

转载 作者:行者123 更新时间:2023-11-28 05:49:08 25 4
gpt4 key购买 nike

不在数组的常设循环之下。循环遍历所有抓取或搜索。有人可以解释这个过程吗?提前致谢。对不起,如果重复。我环顾四周,找不到我能理解的可靠解释。

#include <fstream>
#include <iostream>
#include <string>
#include <cstring>

using namespace std;

void allContacts(string names[], string phones[])
{
cout << "Showing all contacts... Press Q to go back to main menu" << endl;
}

void addName(string names[], string phones[])
{
bool keepGoing;
string input;

beginning:
for (int i = 0; i < sizeof(names); i++)
{
cout << "Enter contact name: ";
cin >> names[i];
cout << "Enter contact number: ";
cin >> phones[i];
cout << "Do you have another contact to add? y or no" << endl;
cin >> input;
if(input == "y" || input == "Y")
{
goto beginning;
}

if(input == "n" || input == "N")
{
cout << "Contacts you have entered: " << endl;
cout << names[i] << " : " << phones[i] << endl;
}
}
}

void searchName(string names[], string phones[])
{
string name;
cout << "Enter Name: ";
cin >> name;

cout << "Search for a name or Press Q to go back to main menu" << endl;

for (int i = 0; i < sizeof(names); i++){
if (name == names[i])
{
cout << counter << names[i] << " 's phone number is: " << phones[i] << endl;
} else {
cout << "No results found";
}
}
}

int main()
{
string names[100];
string phones[100];
int choice;

cout << "============================" << endl;
cout << "=== Welcome to PhoneBook ===" << endl;
cout << "============================" << endl;

cout << "1- Add a New Contact" << endl;
cout << "2- Search By Name" << endl;
cout << "3- Display All" << endl;
cout << "0- Exit" << endl;

cout << "Select a number: " << endl;
cin >> choice;

switch(choice)
{
case 1:
addName(names, phones);
break;
case 2:
searchName(names, phones);
break;
case 3:
allContacts(names, phones);
break;
case 0:
cout << "Exiting PhoneBook...";
break;
}
}

最佳答案

在 C++ 中,数组在传递给函数时会丢失属性。这些属性是容量和大小(已填充插槽的数量)。您需要为每个数组传递此附加信息:

void addName(string names[],  unsigned int names_capacity, unsigned int names_size,
string phones[], unsigned int phones_capacity, unsigned int phones_size)

要解决这个问题,您可以使用 std::vectorstd::vector 知道它的容量和大小,因此您不必将额外的属性传递给您的函数。

另外,如果你在比较之前使用tolowertoupper,你只需要进行一次比较:

char input; 
cout << "Do you have another contact to add? y or n" << endl;
cin >> input;
input = toupper(input);
if(input == 'Y')

在使用字符串时,可以通过std::transform将其全部转为大写或全部转为小写,如:

  std::transform(input.begin(),
input.begin(), input.end(),
tolower);

关于C++ 拉取信息并循环显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35632129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com