将数组作为参数传递给函数

passing arrays as an argument to a function

本文关键字:函数 参数传递 数组      更新时间:2023-10-16

在下面的代码中,我想通过数组输入一些记录,最后想比较字符串的记录以生成输出。没有得到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