[英]String as a sentinel in while loop in C++
我试着做一个使用getchar()
从标准输入中读取短行的函数。 该函数本身确实运行良好,但是当我在while循环中将其用作哨兵的一部分时,总会收到一个错误,简而言之,即它无法从字符串转换为bool。
#include <iostream>
#include <stdio.h>
using namespace std;
string myReadLine();
int main()
{
string str = "";
while ((str = myReadLine()) != NULL) { //eof, and any expression of that sort
cout << str << endl;
}
return 0;
}
string myReadLine() {
string line = "";
char singleSign;
while ((singleSign=getchar()) != '\n') {
line = line + singleSign;
}
return line;
}
我究竟做错了什么? 多谢您的协助!
问题2:您如何看待myReadLine()
函数的效率? 可以吗
如您所说,您不能将字符串转换为布尔值。 我建议:
str = myReadLine();
while (!str.empty())
{
cout << str << endl;
str = myReadLine();
}
在这一行中(假设您错误地在其中键入了一个额外的括号):
while (str = myReadLine() != NULL)
在str = myReadLine()
之前先评估myReadLine() != NULL
。 这就是为什么说str
不能转换为bool
。
将括号放在str = myReadLine()
周围,它应该可以工作。
while (str = myReadLine()) != NULL)
类字符串实例与NULL的比较不正确。 您可以使用指针执行此操作。
这是执行此操作的下一个最佳方法:
#include <iostream>
#include <stdio.h>
using namespace std;
bool myReadLine(string& line);
int main()
{
string str = "";
while (myReadLine(str)){
cout << str << endl;
}
return 0;
}
bool myReadLine(string& line) {
char singleSign;
line = "";
while ((singleSign=getchar()) != '\n') {
line = line + singleSign;
}
return line == "" ? false : true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.