将数组作为参数传递给函数
passing arrays as an argument to a function
在下面的代码中,我想通过数组输入一些记录,最后想比较字符串的记录以生成输出。没有得到compare函数的函数性。请帮忙。。。。。。。。。。。。。。。。。。。
#include <iostream>
#include <string>
using namespace std;
int compare(string record[20], int numb1)
{
system("pause");
int i;
string str, substring;
cout<<"enter the string"<<endl;
getline(cin, str);
for (i=0;i<numb1;i++)
{
if(str == record[i])
{
substring = str.substr(0,2);
}
break;
}
if (substring == 'del')
{
cout<<"you have a delux type"<<endl;
}
else if ('bas' == substring)
{
cout<<"you have a basics type"<<endl;
}
else
{
cout<<"invalid id"<<endl;
}
system("pause");
return 0;
}
int enter_record(int n)
{
int i;
string rec[20];
char choice_1;
for(i=0;i<n1;i++)
{
cout<<"enter value for "<<i+1<<" record"<<endl;
cin>> rec[i];
}
cout <<"ttt FINAL DESIGNED PACKAGES ARE :- "<<endl;
cout <<"ttt ----------------------------"<<endl;
for(i=0;i<n;i++)
{
cout<<i+1<<". "<<rec[i]<<endl;
}
cout<< "tttdo you want to compare an string (y/n)"<<endl;
if ('y' == choice_1)
{
compare(rec, n);
}
system("pause");
return 0;
}
int main()
{
int numb;
cout<<"ttt WELCOME TO TOUR PACKAGE CHECKING"<<endl;
cout<<"ttt --------------------------------"<<endl;
cout<<"enter number of records you want"<<endl;
cin>>numb;
enter_record(numb);
return 0;
}
在C++中,单个记号用于字符。del
不是法律字符。所以你想要的是"del"
,而不是'del'
。但实际上,您应该使用比C样式数组更聪明的东西。
您应该执行substring = str.substr(0,3);
而不是str.substr(0,2);
。请记住第二个参数是子字符串的长度。因此,如果使用2
而不是del
,则会得到de
。这就是为什么,我猜,你变得越来越"强壮"了;无效id"一直。正如@David所说,你还需要修复字符串周围的引号。
当然,您的代码还有其他问题,比如缓冲区溢出。。您假设最多有20条记录,但我可以尝试输入200……接受@chris的建议,使用std::vector
而不是原始字符串数组。
编辑
在处理上述问题之前,您还存在一个逻辑错误。请参阅下面的片段。
cout<< "tttdo you want to compare an string (y/n)"<<endl;
if ('y' == choice_1)
{
compare(rec, n);
}
您要求用户输入,但实际上并没有输入。因此,您正在将未初始化的char
与可能为false的y
进行比较,因此永远不会调用compare函数。
您应该在if
之前添加一个cin>>choice_1
。
相关文章:
- 如何在C++中将迭代器作为函数参数传递
- 为什么我不能将引用作为 std::async 的函数参数传递
- 节点插件 API 将数组作为函数参数传递
- 将字符串数组作为函数参数传递
- 如何通过 C++ 中的函数参数传递初始值设定项列表的固定大小的初始值设定项列表?
- 我可以动态创建新地图并作为函数参数传递吗?
- 将任意模板向量作为函数参数C++传递
- 将函数指针作为函数参数传递的目的
- C++:通过函数参数传递的值给出不同的结果
- 当数组大小在C++中未知时,如何在运行时将对字符串数组的引用作为函数参数传递?
- 通过宏将函数参数传递给函数
- C++:访问作为函数参数传递的双指针数组所指向的变量的值
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- 将派生类构造函数参数传递给受保护的成员
- 将指向数组的指针作为函数参数传递,这本身就是另一个函数的返回值?
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 有什么理由C++ 11+ std::mutex 应该声明为全局变量,而不是作为函数参数传递到 std::thread 中
- 如何将派生类作为函数参数传递:如果派生类成员不在父类中怎么办
- 如何将变量作为构造函数参数或函数参数传递
- 当数组对象以函数参数传递时,为什么复制构造函数会自称