读取文件中.txt特定单词
Reading a particular word in .txt file
我有一个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 33
或sourav 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();
}
相关文章:
- 文本文件中的单词链表
- 如何将 txt 文件中的行分隔为组件C++
- 在指针的帮助下,文本文件中单词的频率
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 如何根据单词在文本中出现的概率输出单词
- 一种在C++中读取TXT配置文件的简单方法
- 如何修复此iFile以将.txt输出到控制台
- 从字符串变量中逐字符读取单词
- 创建程序以从给定的.txt文件中查找文本,替换并计算单词
- 在带有C++的txt文件中查找最长的单词
- C :按行读取txt文件的读数,单词用单词读取,每行的单词不均匀
- 尝试创建一个读取.txt文件,显示它,计数唯一单词的程序,并在使用了多少次的情况下显示独特的单词.C
- 在.txt文件上计算重复单词的C 程序
- 有没有办法在C 中扫描TXT文件中的单词或名称
- C++ 无法读取 txt 文件中的单词
- 在C/C 中显示来自TXT文件的单词
- 读取文件中.txt特定单词
- 从文件中提取行.txt然后将单词存储到单独的数组中 |C++
- txt文件中最常见的单词
- 如何从.txt文件复制单词到数组.然后将每个单词打印在单独的一行上