为什么同时使用两个 getline 函数,第二个不带 \n 字符?
Why does using two getline function together, second one doesn't take the \n character?
#include <bits/stdc++.h>
using namespace std;
int main(){
string str1, str2;
getline(cin, str1); // aaa
getline(cin, str2); // bbb
cout << str1 << " " << str2; // aaa bbb
return 0;
}
为什么我把str1
输入"aaa\n"
时,第二个getline()
不带\n
?
cout
应该打印 "aaa"
而不是 "aaa bbb"
.
来自 cppreference 的 std::getline
的描述(加粗我的):
...until one of the following occurs...
b) the next
available input character is delim, as tested by Traits::eq(c, delim),
in which case the delimiter character is extracted from input, but is
not appended to str.
因此,在您的情况下,每个输入末尾的换行符 从输入流中提取 但 未添加 两个 string
变量。
另外,请看这个:
第一个 std::getline()
读入 aaa
和它后面的换行符,但丢弃换行符。 str1
中没有保存 '\n'
个字符。
第二个 std::getline()
然后读入 bbb
和它后面的换行符,但丢弃换行符。 str2
中没有保存 '\n'
个字符。
#include <bits/stdc++.h>
using namespace std;
int main(){
string str1, str2;
getline(cin, str1); // aaa
getline(cin, str2); // bbb
cout << str1 << " " << str2; // aaa bbb
return 0;
}
为什么我把str1
输入"aaa\n"
时,第二个getline()
不带\n
?
cout
应该打印 "aaa"
而不是 "aaa bbb"
.
来自 cppreference 的 std::getline
的描述(加粗我的):
...until one of the following occurs...
b) the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input, but is not appended to str.
因此,在您的情况下,每个输入末尾的换行符 从输入流中提取 但 未添加 两个 string
变量。
另外,请看这个:
第一个 std::getline()
读入 aaa
和它后面的换行符,但丢弃换行符。 str1
中没有保存 '\n'
个字符。
第二个 std::getline()
然后读入 bbb
和它后面的换行符,但丢弃换行符。 str2
中没有保存 '\n'
个字符。