提问人:Valotron4000 提问时间:11/13/2023 更新时间:11/13/2023 访问量:7
为什么我的 istream 在我用它调用 getline 后变坏了
Why is my istream going bad after I call getline with it
问:
我正在为一个编码类编写代码,我正在编写一个名为 MyString 的类,它应该能够存储一个像 String 一样的动态 char 数组。但是,在编写一个旨在像 getline() 函数一样的 read() 函数时,我在使用 istream 对象调用 getline() 后遇到了错误。通话后,istream对象不再好,我无法弄清楚原因。任何帮助/想法将不胜感激。
以下是 MyString.cpp 文件的错误方法:
//Copys contents of in into calling object up to when the deliminator is found in in
void MyString::read(istream& in, char deliminator)
{
char copyString[MyString::MAX_INPUT_SIZE];
if (in.good())
{
cout << "pre:all good" << endl;
}
else
{
cout << "pre:all bad" << endl;
}
in.getline(copyString, deliminator);
if (in.good())
{
cout << "post:all good" << endl;
}
else
{
cout << "post:all bad" << endl;
}
delete[]theString;
theString = new char[strlen(copyString) + 1];
strcpy(theString, copyString);
}
这是我的主函数调用我的 read() 方法的部分:
cout << endl << "----- now, line by line" << endl;
ifstream in2("mystring.txt");
assert(in2);
while (in2.peek() == '#') {
in2.ignore(128, '\n');
}
if (in2)
{
cout << "in2 is good!" << endl;
}
s.read(in2, '\n');
while (in2) {
cout << "in2 is still good: " << in2.good() << endl;
cout << "Read string = " << s << endl;
s.read(in2, '\n');
}
in2.close();
以下是文本文件:
# This file has some strings that are used in the string test to check
# reading strings from files. The default overloaded >> of your string
# class should skip over any leading spaces and read characters into
# the string object, stopping at the first whitespace character (this is
# similar to the behavior of >> on char *). The read method of the
# string class is a little fancier. It allows client to restrict
# how many characters at max to read and what character to use as
# delimiter, so you can stop at newline instead of space, for example.
# Reading consumes the delimiting character, so the next read starts
# after that.
#
The first time we will
read individual words, next
we read whole lines
我试着摆弄我的参数,并将 istream 更改为 ifstream,但它什么也没做。我添加了 cout 语句来测试错误代码的位置,一旦我发现是 in.getline() 语句使 istream 变坏,我就尝试从那里查找我的问题。我找不到关于这个问题的任何东西,尽管以前肯定有人也遇到过这个问题。 NY的帮助或想法将不胜感激。
答: 暂无答案
评论