gpt4 book ai didi

c++ - seekg 和 tellg 不兼容

转载 作者:行者123 更新时间:2023-11-28 03:39:58 24 4
gpt4 key购买 nike

我正在编写一个 C++ 控制台应用程序。在用 size(int) rowSize 和 columnSize 创建了一个 Matrix 之后,我想将文本文件中的字母写入矩阵,但是 while 循环永远不会运行,因为 reader 的位置是 -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()

关于c++ - seekg 和 tellg 不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9587433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com