覆盖运算符>>对于 Strings 类
我有一个简单的问题。我需要重写运算符>>对于自定义 String 类,我不太清楚该怎么做。
我知道这段代码是有效的,因为这是我解决问题的原始方法:
istream& operator>>(istream &is, String &s) {
char data[ String::BUFF_INC ]; //BUFF_INC is predefined
is >> data;
delete &s;
s = data;
return s;
}
但是,根据规范(这是一项家庭作业),我需要一次读入字符 1 来手动检查空格并确保该字符串对于 data[] 来说不算太大。因此,我将代码更改为以下内容:
istream& operator>>(istream &is, String &s) {
char data[ String::BUFF_INC ];
int idx = 0;
data[ 0 ] = is.get();
while( (data[ idx ] != *String::WHITESPACE) && !is.ios::fail() ) {
++idx;
is.get();
data[ idx ] = s[ idx ];
}
return is;
}
但是,当执行此新代码时,它只会陷入用户输入的循环中。那么如何使用 is.get() 逐个字符地读入数据而不等待更多的用户输入呢?或者我应该使用 .get() 以外的其他东西?
I just have a quick question. I need to override the operator >> for a custom String class and I can't quite figure out how to do it.
I know that this code works, because it was my original method of solving the problem:
istream& operator>>(istream &is, String &s) {
char data[ String::BUFF_INC ]; //BUFF_INC is predefined
is >> data;
delete &s;
s = data;
return s;
}
However, according to the spec (this is a homework assignment), I need to read in the characters 1 at a time to manually check for whitespace and ensure that the string isn't too big for data[]. So I changed my code to the following:
istream& operator>>(istream &is, String &s) {
char data[ String::BUFF_INC ];
int idx = 0;
data[ 0 ] = is.get();
while( (data[ idx ] != *String::WHITESPACE) && !is.ios::fail() ) {
++idx;
is.get();
data[ idx ] = s[ idx ];
}
return is;
}
When this new code is executed however it just gets stuck in a loop of user input. So how do I use is.get() to read in the data character by character but not wait for more user input? Or should I perhaps be using something other than .get()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您似乎没有对从流中获取的字符执行任何操作,
因此它检查字符串 s 是否包含空格,而不是您是否从流中读取空格。
You don't seem to be doing anything with the character you get from the stream
So it checks whether the string s contains a whitespace, not whether you read a whitespace from the stream.
尝试:
评论您的原始代码:
使用第二个版本作为基础:
Try:
Commenting on your original code:
Using the second version as a base: