读取文件中.txt特定单词

Reading a particular word in .txt file

本文关键字:单词 txt 文件 读取      更新时间:2023-10-16

我有一个txt文件,其中包含学生的姓名和卷号。我想从他的文件中读取并显示特定的卷号。它只显示第一个卷号,但我想阅读第二个人的卷号。

也就是说,如果我想读取"ss"的卷号,它会显示第一个人的卷号

该程序是

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
#include<stdio.h>
void student_read()
{
    clrscr();
    char name[30], n[30], temp[30];
    int i, roll_no, code, count=0;
    ifstream fin("tt.txt",ios::in|ios::beg);
    if(!fin)
    {
        cout << "cannot open for read ";
        return;
    }
cout << "Enter the name of student" << "n";
        cin >> n;
    while(fin >> name >> roll_no)
    {
        cout << roll_no << endl;
    }

    if(string[name] == string[n])
    {
        cout << "roll no" << "n" << roll_no;
    }
    else
        cout << "Not found";
}
void main()
{
    clrscr();
    cout << "Students details is" << "n";
    student_read();
    getch();
}

txt 文件包含以下数据:

苏拉夫123党卫军33

文本文件中的每一行都有结尾吗?你有sourav 123 ss 33sourav 123nss 33吗?这if(n[30]==name[30])仅比较字符串中的 1 个字符。

在输入要搜索的名称之前,您已经在执行文件中内容的输出。

对语句重新排序,如下所示:

cout<<"Enter the name of student"<<"n";
cin>>n;
while(fin>>name>>roll_no)
{
    //...

此外,如果您只想输出一个名称和roll_no,则必须在循环中检查是否打印某种条件。目前,您的代码实际上应该打印文件中所有行的roll_no,有时可能打印最后一行两次。

因此,输入后的条件属于循环。

但是,此外,您只是比较 char 数组的第 31 个字符(实际上已经超出了数组变量的范围!它们的索引从 0..29 开始,即即使您分配了一个 30 个字符的数组,.这意味着,如果倒数第二个字符匹配,则条件将为真。这个地方很可能还没有初始化,所以你比较基本上是gargabe值,会得到意外/随机的结果。

如果你想,如描述所示,想要比较整个 char 数组,顺便说一下,它的工作方式不同(不使用 == 运算符,它只会比较指针地址),你需要使用 strcmp 函数。但更好的是使用 std::string 而不是 char * .

void student_read()
{
    clrscr();
    std::string name, n, temp;
    int i, roll_no, code, count = 0;
    std::ifstream fin("tt.txt", ios::in | ios::beg);
    if (!fin)
    {
        std::cout << "cannot open for read ";
        return;
    }
    std::cout << "Enter the name of student" << "n";
    std::cin >> n;
    while (fin >> name >> roll_no)
    {
        std::cout << roll_no << std::endl;
    }
    if (name == n)
    {
        std::cout << "roll no" << "n" << roll_no;
    }
    else
        std::cout << "Not found";
}
int main()
{
    clrscr();
    std::cout << "Students details isn";
    student_read();
    getch();
}