字符串c++的经验湖

strings c++ lake of experience

本文关键字:经验湖 c++ 字符串      更新时间:2023-10-16

我正试图编辑列表中联系人的号码发生变化的联系人,并使用临时字符串进行编辑,但在从用户那里获取临时字符串的步骤中,它崩溃了,我不知道原因可能是我的经验不足

样本输入:3.Abdelrahman Elgammal+1(202)417-0330库克门16999Ahmed Naguib 01234567892.Abdel-Rahman ElGammal+1(305)951-1169Ahmed Naguib 0020123456788

样本输出:Abdel-Rahman ElGammal+1(305)951-1169库克门16999Ahmed Naguib 0020123456788这是我的代码:

#include <iostream>
#include <vector>
#include <string.h>
using namespace std;

struct contact
{
    string first_name;
    string last_name;
    string phone_number;
};
int main(int argc, char** argv)
{
    int n,m,i;
    cin>>n;
    vector <struct contact> contacts(n);
    string temp_first;
    string temp_last;
    string new_phone;
   for(i=0;i<contacts.size();i++)
    {
    cin>>contacts[i].first_name;
    cin>>contacts[i].last_name;
    cin>>contacts[i].phone_number;
    }
   cin>>m;
   for(int j=1;j<=m;j++)
    {
      cin>>temp_first;
      cin>>temp_last;
      cin>>new_phone;
      for(int k=0;k<contacts.size();k++)
      {
        if(temp_first==contacts[i].first_name&&temp_last==contacts[i].last_name)
            contacts[i].phone_number=new_phone;
    }
}
    for(int p=0;p>contacts.size();p++)
    {
       cout<<contacts[i].first_name<<" "<<contacts[i].last_name<<" "   <<contacts[i].phone_number<<endl;
    }

    return 0;
}

原因是这个循环中的一个微不足道的拼写错误:

for(int k=0;k<contacts.size();k++)
{
  if(temp_first==contacts[i].first_name&&temp_last==contacts[i].last_name)
    contacts[i].phone_number=new_phone;
}

它应该是contacts[k]而不是contacts[i]

您在for(int p...循环中也有同样的拼写错误。此外,该循环条件应该是p < contacts.size()

这是一个支持保持变量范围,特别是循环索引尽可能小的论点。与其声明int i对整个main可见,不如将其限制在使用它的for循环中,这样您就可以在编译时发现这个问题。

此外,尽可能使用C++11的基于范围的循环。例如,使用新语法重写上面的一个错误循环

for(auto& contact : contacts)
{
  if(temp_first==contact.first_name && temp_last==contact.last_name)
    contact.phone_number=new_phone;
}