[英]How do I stop reading a newline from a string?
我必须找到一种方法来显示给定文本的第二行。 如果文本长度少于两行,则应显示“文本不够长”。 我最初的解决方案是使用getline()
function 两次,但在线评估员拒绝通过其中一项测试。
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string a;
getline(cin,a);
getline(cin,a);
if(a.length())
cout << a;
else
cout << "text not long enough";
}
你能发现问题并提出解决方案吗?
if(a.length())
行应该完成什么? 它只是检查字符串a
是否包含至少一个字符。
在你写的伪代码中:
if a has at least one character then
print a
else
print "text not long enough"
那是因为如果 length 为 0 它会转换为false
,那么每隔一个数字就会被认为是true
。
正如约翰所写:
if (getline(cin, a) && getline(cin, a))
cout << a;
else cout << "text not long enough";
这大致翻译为:
bool isInputTwoLinesLong()
{
int newlines = 0;
char c;
while(cin >> c)
{
if (c == '\n') newlines++;
// input contains at least two lines
if (newlines == 2) return true;
}
// input not long enough
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.