字符串c++的经验湖
strings c++ lake of experience
我正试图编辑列表中联系人的号码发生变化的联系人,并使用临时字符串进行编辑,但在从用户那里获取临时字符串的步骤中,它崩溃了,我不知道原因可能是我的经验不足
样本输入: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;
}
相关文章:
- 何时返回指针与返回对象的一般经验法则?
- 私有变量无法正常工作的C++getter方法(只有Java经验)
- 点云库 (PCL) - 声明点云时何时应使用 ::P tr 的经验法则?
- 本机C 库与UWP的建议/经验
- 是按值抛出和按引用捕获的经验法则
- 并发::并行端口开销和性能命中率(经验法则)
- 新建和删除的经验法则
- 实现经验 CDF C++
- 字符串c++的经验湖
- 使用 /O2 与 /Ox 编译 -- 后者更快(根据经验)
- 在C++中使用指针或引用作为函数的返回类型是否有经验法则
- 了解C++语法,适合有经验的 C 程序员
- 当通过值传递比通过常量引用传递快时的经验法则
- 标准库/模板化容器的常量语义的经验法则
- 有经验的程序员对closesocket()的关注
- C++构造函数重载的经验法则
- 当“虚拟”是一个相当大的开销时,有什么经验法则吗
- 指纹SDK经验
- 经验确定c++ 11表达式的值类别
- 向量错误抛掷分配经验甚至不访问任何元素