你不能eof()
像你一样使用。您必须先执行 I/O 读取操作,然后才能使用eof()
.
对于您正在尝试的内容,您应该std::getline()
改用,例如:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <algorithm>
int main()
{
std::ifstream file("file.txt");
std::string line;
char c[20][20] = {};
for (int i = 0; i < 20; ++i)
{
if (!std::getline(file, line))
break;
std::istringstream iss(line);
for(j = 0; j < 20; ++j)
{
if (!(iss >> c[i][j]))
break;
}
}
...
return 0;
}
话虽如此,您应该考虑使用std::vector
而不是固定大小的数组(除非您知道您的文件永远不会超过 20 行和/或每行 20 个字符):
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <vector>
int main()
{
std::ifstream file("file.txt");
std::vector<std::vector<char> > c;
std::string line;
while (std::getline(file, line))
{
std::istringstream iss(line);
std::vector<char> tmp;
std::copy(
std::istream_iterator<char>(iss),
std::istream_iterator<char>(),
std::back_inserter(tmp)
);
/* which is equivalent to:
char ch;
while (iss >> ch) {
tmp.push_back(ch);
}
*/
c.push_back(tmp);
}
...
return 0;
}
或者:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <iterator>
#include <algorithm>
#include <vector>
typedef std::vector<char> CharVector;
std::istream& operator>>(std::istream &in, CharVector &out)
{
out.clear();
std::string line;
if (std::getline(in, line))
{
std::istringstream iss(line);
std::copy(
std::istream_iterator<char>(iss),
std::istream_iterator<char>(),
std::back_inserter(out)
);
/* which is equivalent to:
char ch;
while (iss >> ch) {
out.push_back(ch);
}
*/
}
return in;
}
int main()
{
std::ifstream file("file.txt");
std::vector<CharVector> c;
std::copy(
std::istream_iterator<CharVector>(file),
std::istream_iterator<CharVector>(),
std::back_inserter(c)
);
/* which is equivalent to:
CharVector cv;
while (file >> cv) {
c.push_back(cv);
}
*/
...
return 0;
}