我试图将真值表复制到2D矢量中。第一个数字是表的输入数,所以我接受第一行,然后我开始填充向量。这是来自sample.txt的真值表:
4
0 0 0 0 1
0 0 0 1 0
0 0 1 0 1
0 0 1 1 1
0 1 0 0 0
0 1 0 1 1
0 1 1 0 0
0 1 1 1 0
1 0 0 0 1
1 0 0 1 0
1 0 1 0 0
1 0 1 1 1
1 1 0 0 1
1 1 0 1 0
1 1 1 0 1
1 1 1 1 0
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <math.h>
#include <vector>
#include <fstream>
using namespace std;
string getFileName();
string userFile;
fstream file;
int width;
vector < vector <int> >newArray; // 2d array as a vector of vectors
int main() {
vector < vector <int> >array; // 2d array as a vector of vectors
int row = 0; // Row counter
int col = 0;
int count = 0;
int add = 0;
userFile = getFileName();
// Read file
file.open(userFile.c_str(), ios::in); // Open file
if (file.is_open()) { // If file has correctly opened...
// Output debug message
cout << "File correctly opened" << endl;
string nLine;
string line;
getline(file, nLine);
width = atoi(nLine.c_str());
cout << "Width: " << width << endl;
// Dynamically store data into array
while (getline(file, nLine)) { // ... and while there are no errors,
vector <int> rowVector(width-1); // vector to add into 'array' (represents a row)
array.push_back(rowVector); // add a new row,
cout << "row" << row <<": ";
col = 0;
for(std::string::size_type i = 0; i < nLine.size(); ++i) { //iterate string
if(nLine[i] == '1'){
array[row][col] = 1;
cout << " Col " << col << ": " << array[row][col];
col++;
}
else if(nLine[i] == '0'){
array[row][col] = 0;
cout << " Col " << col << ": " << array[row][col];
col++;
}
else{ //skip spaces
}
}
cout << endl;
row++; // Keep track of actual row
}
}
else cout << "Unable to open file" << endl;
file.close();
cout << "Copied" << endl;
for(int i = 0; i < row; i++){
for(int j = 0; j <= width; j++){
cout << array[i][j] << " ";
}
cout << endl;
}
//erase lines that have output of 0
// for(int i = 0; i < row; i++){
// if(array[i][width] == 0){
// cout << i << " " << array[i][width]<< endl;
// array.erase(array.begin() + i);
// count++;
// }
// }
row -= count;
cout << "New rows: " << row << endl;
return 0;
}
string getFileName(){
cout << "Enter file name pls: " << endl;
cin >> userFile;
file.open(userFile.c_str(), ios::in); // Open file
if (file.is_open()) { // If file has correctly opened...
cout << "File correctly opened" << endl;
}
else {
cout << "Unable to open file" << endl;
getFileName();
}
file.close();
return userFile;
}
以下是执行的截图:
当我将它们放入向量时输出它们时,行和列似乎都是正确的,但是当我回去时,前8行左右是完全错误的,其余的都是正确的...我是不知道为什么。我在if(file.is_open())语句之后关闭文件(第67行)后立即打印它。
感谢您的帮助, 一切顺利
答案 0 :(得分:1)
在这一行
vector <int> rowVector(width-1); // vector to add into 'array' (represents a row)
您声明rowVector
的大小为width-1
,在此测试用例中,您的width
为4
,因此rowVector
的大小为3.但是您的测试case包含5列0
或1
。因此,您尝试访问显示未定义行为的超出范围索引。
要解决此问题,请将rowVector
大小等于width+1
vector <int> rowVector(width+1); // vector to add into 'array' (represents a row)