【问题标题】:C++ Search A Text File and Output the line that matches the search termC ++搜索文本文件并输出与搜索词匹配的行
【发布时间】:2018-06-29 15:38:33
【问题描述】:

我制作了一个文本文件并向其中添加了一些数据。我正在尝试搜索文本文件,在本例中为学生 ID,并输出与该学生 ID 匹配的行。否则输出“未找到学生”

我已经设法搜索和输出,但我无法输出与搜索到的 id 匹配的特定行。

这是我的代码:

#include <iostream>
#include <fstream> 
using namespace std;

int main(){
    char line[500];
    char search[20];
    int i;

    cout<<endl<<"Student Details"<<endl<<endl;

    ifstream infile;

    infile.open("students.txt");
    cout<<"Search: ";
    cin>>search;

    if (infile.is_open() ){
        while ( !infile.eof() ){
            infile.getline(line, 500, ',');
            if ( search[i] == line[i]){
                    while ( !infile.eof() ){
                            infile.getline(line, 500, ',');
                            cout<<line<<endl;   
                        }
            }   
        }
    }
        infile.close();
} 

这是我在搜索后想要得到的输出类型

ID:H173770

姓名:三岛但丁

年龄:20

课程:网页设计

地址:格里莫广场 13 号

【问题讨论】:

标签: c++ file search output


【解决方案1】:

if ( search[i] == line[i]){

您使用 i (int var) 但您从未定义 i = 0 并使用 i++。 Var i 包含“随机”数字,程序在执行 search[i] == line[i] 时失败,因为 i 大于 20。

另外,在行尾,没有 ',' 而是 '\n'。

试试这个:

#include <iostream>
#include <fstream>

using namespace std;

int main(){
    char line[500];
    char search[20];
    int i;

    cout<<endl<<"Student Details"<<endl<<endl;

    ifstream infile;

    infile.open("students.txt");
    cout<<"Search: ";
    cin>>search;

    if (infile.is_open() ){
        while ( !infile.eof() )
        {
            infile.getline(line, 500, ','); // read first line to first ','
            for (i = 0;line[i] == search[i];i++)
            {
                if (search[i] == '\0') // if true search and line is same
                {
                    // print all info
                    cout << "Match found!" << endl;
                    cout << line << endl;
                    infile.getline(line, 500, ',');
                    cout << line << endl;
                    infile.getline(line, 500, ',');
                    cout << line << endl;
                    infile.getline(line, 500, ',');
                    cout << line << endl;
                    infile.getline(line, 500, '\n'); // end of line
                    cout << line << endl;
                    return 1;
                }
            }
            // no match
            for (int j = 0;j < 3;j++) infile.getline(line, 500, ','); // skip the line
            infile.getline(line, 500, '\n'); // we reach end of line
        }
        cout << "Match not found!" << endl;
    }
    else
    {
        cout << "Unable to open: students.txt" << endl;
    }
    infile.close();
    return 0;
}

如果您对代码有任何疑问,请在评论中提问。

【讨论】:

  • 谢谢,这有帮助。但我不明白这些行: for (int j = 0;j
  • 如果我在文本文件中有更多条目,j
  • for (int j = 0;j
  • 好的,我现在明白了:再次感谢您
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-12
  • 2017-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多