【发布时间】:2014-12-25 17:56:02
【问题描述】:
我正在尝试从文件中读取以填充二维向量(向量的向量)。
void readFromFile()
{
string str;
ifstream fileToOpen("test.txt");
if (fileToOpen.is_open())
{
resetBoard();
height=count(istreambuf_iterator<char>(fileToOpen),istreambuf_iterator<char>(), '\n');
length=height*2-1;
cout<<board.size()<<endl;
while(getline(fileToOpen,str))
{
cout<<"inside while\n";
stringstream ss(str);
int i;
vector<short unsigned> line;
while (ss>>i)
{
line.push_back(i);
}
board.push_back(line);
}
fileToOpen.close();
//board.shrink_to_fit();
}
else
cout<<"Unable to open file!\n";
print();
}
您可以忽略大多数与实际文件打开和读/写向量无关的代码。问题首先是while循环似乎没有执行
while(getline(fileToOpen,str))
{
cout<<"inside while\n";
cout 语句永远不会触发,我只是想不通为什么会这样那一点
我的文本文件
0000000000000001000000000000000
0000000000000011100000000000000
0000000000000110010000000000000
0000000000001101111000000000000
0000000000011001000100000000000
0000000000110111101110000000000
0000000001100100001001000000000
0000000011011110011111100000000
0000000110010001110000010000000
0000001101111011001000111000000
0000011001000010111101100100000
0000110111100110100001011110000
0001100100011100110011010001000
0011011110110011101110011011100
0110010000101110001001110010010
1101111001101001011111001111111
【问题讨论】:
-
使用流迭代器调用
std::count()后,流中的位置在末尾。使用length或height有什么意义? -
@0x499602D2 这些变量是全局类变量,在方法外使用
标签: c++ file-io vector getline