C++ 文件处理中的字符串搜索
我正在搜索学生记录,如学生id、班级、部门、性别、电子邮件和电话号码。但此代码无法打开文件并执行搜索 代码C++ 文件处理中的字符串搜索,c++,C++,我正在搜索学生记录,如学生id、班级、部门、性别、电子邮件和电话号码。但此代码无法打开文件并执行搜索 代码 这会让你得到你想要看到的。我让你检查以确保文件被正确打开。另外,如果没有找到记录,让用户知道可能会有帮助 #include <iostream> #include <fstream> #include <string> #include <sstream> using namespace std; int main() { ifst
这会让你得到你想要看到的。我让你检查以确保文件被正确打开。另外,如果没有找到记录,让用户知道可能会有帮助
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main() {
ifstream in("Student.txt");
int target_id, id;
cin >> target_id;
string record, field;
// while there are records in the file
while(getline(in, record)) {
istringstream ss(record);
ss >> id;
// Check to see if target id equals record id
if(target_id == id) {
cout << id;
// It does, so let's print the rest of the fields
while(getline(ss, field, ',')) {
cout << field << " ";
}
cout << endl;
}
}
in.close();
return 0;
}
这是毫无疑问的。这在某种程度上不起作用吗?请提供错误消息,或者您的预期输出与实际输出。文件的结构是什么?那你有什么问题?不要这样做!这几乎总是错的。取而代之的是在getline时执行…您的输入文件是如何格式化的?这里没有问题。
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main() {
ifstream in("Student.txt");
int target_id, id;
cin >> target_id;
string record, field;
// while there are records in the file
while(getline(in, record)) {
istringstream ss(record);
ss >> id;
// Check to see if target id equals record id
if(target_id == id) {
cout << id;
// It does, so let's print the rest of the fields
while(getline(ss, field, ',')) {
cout << field << " ";
}
cout << endl;
}
}
in.close();
return 0;
}