如何使用strstr()?

时间:2014-08-19 10:11:21

标签: c++ strstr

我想从文件中获取数据并将其存储在字符串数组中,并执行搜索功能,只需要很少的信息,例如类型" j"并且该程序能够查找包含" j"的数据名称。 但我的程序无法工作..... 我想知道我是否正确使用了strstr()?

我的文字档案:

Jason Derulo
5000
Martin Delux
8752
Justin Haber
51855
Alex Zander
52163

编码:

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

using namespace std;
//---------------------------------------------------------------------------------------------------------
typedef struct
{

    char name[30],adv_srh_name[30];
    double balance;

}ACCOUNT;


int main()
{
    ACCOUNT record[31]; 
    int choice,acc_amount=0;

    ifstream openfile("list.txt");              //open text file 
    if (!openfile)
    {
        cout << "Error opening input file\n";
        return 0;
    }

    else
    {
        ACCOUNT temp;
        int i = 0;
        double d = 0;

        while (openfile)
        {
            openfile.getline(temp.name, 30, '\n');

            //consume the newline still in the stream:    
            if ((openfile >> d).get()) { temp.balance = d; }

            record[i] = temp;
            i++;
        }
        openfile.close();               //close text file
        acc_amount = i;
    }

    cout << "Please enter a client name:";
        fflush(stdin);
        cin.getline(adv_srh_name, 30);

        for (int j = 0; adv_srh_name[j] != NULL; j++)
            adv_srh_name[j] = toupper(adv_srh_name[j]);

        cout << adv_srh_name;

        for (int a = 0; a < acc_amount; a++)
        {
            if ((strstr(record[a].name, adv_srh_name)) != NULL)
            {
                cout << "Name :" << record[a].name << "\n";
                cout << "Balance :" << record[a].balance << "\n\n";
            }

        }
        return 0;
    }

0 个答案:

没有答案