[英]Problems with reading a text-file and putting the tokens into a 2D matrix
我在讀取文本文件並將令牌從文本文件放入二維矩陣時遇到問題。
這是我的代碼:
std::vector< vector <std::string> > my_matrix(10, vector <std::string>(10));
ifstream myReadFile;
myReadFile.open("class_data.txt", ios_base::in);
char output[100];
if (myReadFile.is_open()) {
if (!myReadFile.eof()) {
myReadFile >> output;
char* token = NULL;
char* context = NULL;
char delims[] = " ,\t\n";
token = strtok_s(output, delims, &context);
if (token != NULL)
{
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
my_matrix[i][j] = *token;
cout << "token = " << token << endl;
cout << "matrix = " << my_matrix[i][j] << endl;
token = strtok_s(NULL, delims, &context);
}
}
}
}
}
std::cout.width(3); std::cout << left << "ID";
std::cout.width(9); std::cout << left << "Project1";
std::cout.width(9); std::cout << left << "Project2";
std::cout.width(9); std::cout << left << "Project3";
std::cout.width(9); std::cout << left << "Project4";
std::cout.width(9); std::cout << left << "Project5";
std::cout.width(9); std::cout << left << "Project6";
std::cout.width(9); std::cout << left << "Project7";
std::cout.width(9); std::cout << left << "Midterm";
std::cout.width(9); std::cout << left << "Final" << std::endl;
std::cout << "-------------------------------------------------------------------------------" << std::endl;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
cout.width(10); std::cout << my_matrix[i][j];
}
std::cout << " " << std::endl;
}
我沒有錯誤,它可以編譯,但是在程序中,當我想顯示二維矩陣時,它不顯示它。 它對整個矩陣沒有價值。
誰能幫我一下,告訴我這是什么問題? 是我執行2 for循環的方式還是閱讀文本文件的方式? 如果發現問題,任何人都可以提出解決方案。
PS對不起,如果我沒有最好的專業代碼,但是我是C ++的初學者,並且沒有參加任何大學水平的編程課程。
您已經有一個10x10的矩陣,並且strtok將char *返回給當前令牌,只需將其傳遞給矩陣中的std :: string operator =,如下所示:
my_matrix[i][j] = token;
您還需要重新考慮循環中的邏輯。 在內部for的strtok調用之后,添加對返回值的檢查,如果返回值為NULL,則從兩個循環中中斷。 用if測試替換while循環。
編輯:
我看到您將while更改為if,但是,2 for循環也需要稍作更改。 我建議是這樣的:
for (int i = 0; i < 10 && token; i++) {
for (int j = 0; j < 10 && token; j++) {
my_matrix[i][j] = token; // NOTE: not *token here
cout << "token = " << token << endl;
cout << "matrix = " << my_matrix[i][j] << endl;
token = strtok_s(NULL, delims, &context);
}
}
此更改還使循環前的if測試變得不必要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.