我有一个文件,其中包含.txt文件中周期表中的信息,我试图编写一个程序,允许用户输入元素符号,然后通读文件,直到找到该符号并吐出有关该符号的信息元件。最初,我得到了程序来输出不带任何信息的cout语句,现在,在输入符号后,它完全跳过了本节,直接转到下一个。这是我的代码。
ifstream fin;
ofstream myfile;
string line;
myfile.open("txt file");
fin.open("txt file", ios::app);
while (std::getline(fin, line)) {
fin >> element >> symbol >> atomic_number >> atomic_mass >> physical_state >> density >> melting_point >> boiling_point >> created >> chemical_group >> electronegativity;
if (line == symbol)
{
cout << "information from above"
break;
}
fin.close();
myfile.close();
}
答案 0 :(得分:0)
尝试读取.txt文件并根据用户输入的字母拉出特定的行。
这是示例代码:
#include <iostream>
#include"string"
#include <fstream>
using namespace std;
int main(void)
{
ifstream fi("1.txt", ofstream::in);
ofstream fo("2.txt", ofstream::out);
string buf;
string s1;
cin >> s1;
while (fi >> buf)
{
if (buf.find(s1) != string::npos) break;
}
fo << buf << endl;
fi.close();
fo.close();
return 0;
}
1.txt是您尝试读取的文件。将拉出特定行保存到2.txt。 “ s1”是用户输入的字符串。
希望此代码对您有所帮助。