#include <iostream> #include <fstream> #include <string> #include<stdlib.h> #include<algorithm> using namespace std; int main() { fstream datafile; int i; string filename,line[100],name[100],searchname,name1[100]; cout << "Enter the FULL name of the file: "; cin >> filename; datafile.open(filename.c_str(), fstream::in); if (datafile.is_open() == false) { cout << "ERROR: not able to open " << filename << endl; } else { int number = 0; while (getline(datafile, line[number])) { number++;} cout<<"enter the name you search:"; cin>>searchname; for(int i=0;i<number;i++) { int sea=line[i].find(searchname); if(sea==-1) { cout<<"error:do not find this name"<<endl; }else { while(line[i]!=";") { name1[i]=line[i]; } int mao=line[i].find(';'); int total=line[i].length(); if(name1[i]==searchname) { cout<<line[i].substr(mao+1,total); } } } datafile.close(); } system("pause"); return 0; } 这段代码有什么问题 如何改正
时间: 2023-11-28 21:50:31 浏览: 68
这段代码的问题在于:
1. 在循环中没有对name1数组进行初始化,可能会导致出现未定义的行为。
2. 在找到搜索名字后,没有对name1数组进行更新。
3. 在找到搜索名字后,直接输出line[i]后面的内容,而不是输出name1[i]后面的内容。
4. 在读取文件名时,应该使用getline(cin, filename)而不是cin>>filename,以避免在文件名中包含空格时出现问题。
改正后的代码如下:
```
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <algorithm>
using namespace std;
int main() {
fstream datafile;
int i;
string filename, line[100], name[100], searchname, name1[100];
cout << "Enter the FULL name of the file: ";
getline(cin, filename);
datafile.open(filename.c_str(), fstream::in);
if (datafile.is_open() == false) {
cout << "ERROR: not able to open " << filename << endl;
} else {
int number = 0;
while (getline(datafile, line[number])) {
number++;
}
cout << "Enter the name you search: ";
cin >> searchname;
for (int i = 0; i < number; i++) {
int sea = line[i].find(searchname);
if (sea == -1) {
continue;
} else {
int j = 0;
while (line[i][j] != ';') {
name1[i] += line[i][j];
j++;
}
int mao = line[i].find(';');
int total = line[i].length();
if (name1[i] == searchname) {
cout << line[i].substr(mao + 1, total) << endl;
}
}
}
datafile.close();
}
system("pause");
return 0;
}
```
阅读全文