我正在做这个项目,而且我对 C++ 还是很陌生。很难解释我正在尝试做什么,但我会尝试。所以我正在使用一个名为 flix.txt 的文件,它看起来如下所示:
1 A 5
1 B 4
1 D 3
1 F 5
2 A 1
3 E 3
3 F 1
4 A 2
第一列是人物(我的对象),第二列是电影,第三列是对象给出的评分。
我试图首先从每一行中提取第一个 int 并使用“operator new”创建一个对象。然后我正在拍摄一部电影并将其转换为一个 int,以便我可以将评级插入一个数组。对不起,如果这听起来令人困惑。这是我现在拥有的代码:
//flix program
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#define NUMBER_OF_MOVIES 6
using namespace std;
int tokenize(string line);
int getMovieNum(char movie);
void resetPos(istream& flix);
class Matrix{
public:
int movieRate[NUMBER_OF_MOVIES];
};
int main(){
int distinctCount = 0;
int checker = -1;
int check = 0;
string line;
int personNum;
char movie;
int rating;
int movieNum;
ifstream flix("flix.txt");
ofstream flick("flix1.txt");
//identify distinct account numbers in file
while(getline(flix, line)){
check = tokenize(line);
if(check != checker)
distinctCount++;
checker = check;
check = 0;
}
//reset position in file
resetPos(flix);
//create objects in accordance with distinct numbers
Matrix* person = new Matrix[distinctCount];
for(int i = 0; i < distinctCount; i++){
for(int j = 0; j < NUMBER_OF_MOVIES; j++){
person[i].movieRate[j] = 0;
cout << i + 1 << ' ' << person[i].movieRate[j] << endl;
}
cout << "\n";
}
//reset position in file
resetPos(flix);
//get data from file and put into respective variables
while(getline(flix, line)){
flix >> personNum >> movie >> rating;
cout << personNum << ' ' << movie << ' ' << rating << endl;
//changes the char into an int
movieNum = getMovieNum(movie);
person[personNum].movieRate[movieNum] = rating;
}
//reset position in file
resetPos(flix);
//input ratings into movie array
for(int i = 0; i < distinctCount; i++){
for(int j = 0; j < NUMBER_OF_MOVIES; j++){
cout << i + 1 << ' ' << person[i].movieRate[j] << endl;
flick << i + 1 << ' ' << person[i].movieRate[j] << endl;
}
}
//write data to text file
//??
flick.close();
//free memory
delete[] person;
system("pause");
return 0;
}
int tokenize(string line){
string myText(line);
istringstream iss(myText);
string token;
getline(iss, token, ' ');
int strInt = atoi(token.c_str());
return strInt;
}
int getMovieNum(char movie){
int movieNum = 0;
switch(movie){
case 'A':
movieNum = 1;
break;
case 'B':
movieNum = 2;
break;
case 'C':
movieNum = 3;
break;
case 'D':
movieNum = 4;
break;
case 'E':
movieNum = 5;
break;
case 'F':
movieNum = 6;
break;
default:
movieNum = 0;
break;
}
return movieNum;
}
void resetPos(istream& flix){
flix.clear();
flix.seekg(0);
}
如果这里有noobish错误,我也提前道歉。
我认为问题出在while循环的某个地方,这就是它不断锁定的地方。我花了几个小时在这上面,我不知道为什么它不起作用。在 while 循环中,我试图访问文件的每一行,从行中获取数据,获取电影字符并将其转换为 int,然后将数据插入对象内的数组中。当我确实让它工作时,所有数据也都是错误的。任何输入都受到高度赞赏。提前致谢。