参见kg并告知不相容性
seekg and tellg miscompatibility
我正在编写一个C++控制台应用程序。在创建了一个大小为(int)rowSize和columnSize的矩阵后,我想把文本文件中的字母写到矩阵中,但由于阅读器的位置是-1,所以循环永远不会运行,我无法将其设为0。有什么想法吗?
void writeText2Vec(ifstream & reader, tmatrix<char> & table){
string s;
int length, row = 0, column = 0; //beginning: column and
//row ids are set to 0.
reader.seekg(0); //reset the pointer to start
cout << reader.tellg(); // it results in -1.
while (getline(reader,s)){
//for each line while loop occurs.
length = s.length();
for(column = 0; column < length; column++)
{
table[row][column] = s.at(column);
//writing the letter to matrix.
}
row++;
}
bool openFile(ifstream & reader, string filename){
reader.open(filename.c_str());
if (reader.fail()){
exit("File cannot be found.");
return false;
}
else {
return true;
}
}
bool check(ifstream & reader, int & rowSize, int & columnSize){
//checks for valid characters, if they are
//alphabetical or not and for the length.
string s;
int len = 0, max = 0;
while (getline(reader,s)){
//runs for every line.
rowSize++; //calculation of row size
while (len < s.length()){
if (!(isalpha(s.at(len)))){
// Check to see if all characters are alphabetic.
exit("Matrix contains invalid characters!");
return false;
}
len++;
}
if (max == 0){
//if max is not set.
max = len;
len = 0;
}
else if (!(max == len)){
//if they are different, then appropriate
//error message is returned.
exit("Matrix is not in a correct format!");
return false;
}
else {
//else it resets.
len = 0;
}
}
rowSize -= 1;
columnSize = s.length(); //the last length is equal to column size
return true;
}
tellg()
在出现错误时返回-1
。溪流调用函数时可能处于错误状态。如果你读过直到最后一次,然后有一个输入失败,流是处于错误状态,在任何其他操作工作之前必须清除:reader.clear()
。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 我的神经网络不起作用 [XOR 问题]
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- QSqlquery prepare()和bindvalue()不工作
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 检查输入是否不是整数或数字
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 不带大括号的枚举形式
- 类型的C 参数与父母和子类的类型参数不相容
- 参见kg并告知不相容性