这是几个因素的组合。
读取输入中的第一个数字3,不会将“光标”移动到下一行;它只是将其移过数字。下次调用 getline 时,它会返回大小为 0 的 std::string,因为它会抓取字符末尾和行尾之间的空间,这没什么。
然后,因为您使用该数字作为要读取的字符串的明确数量,所以您正在读取 3 行:""、"aaaa aaa aa" 和 "bb b bbbb"。
因此您的输出缺少'c' 的行。
这里最简单的解决方案是在调用calling 之前强制额外调用getline。 (我已经从你的代码中删除了using namespace std;,因为它是bad practice)
int main() {
int n;
std::cin >> n;
std::string line;
std::getline(std::cin, line);
然后,我们可以重写calling,使其不需要整数参数:
std::vector<std::string> calling(){
std::vector<std::string> file;
std::string line;
while(std::getline(std::cin, line)){
file.push_back(std::move(line));
}
return file;
}
(如果您在控制台中进行测试,并且需要标记行尾的内容,请在 Windows 上使用 Ctrl+Z 或 Ctrl+D 在 UNIX 上。)
这将调用行更改为:
std::vector<std::string> hrml = calling();
或者,如果您使用的是 C++11(并且不介意丢失显式可见的类型声明):
auto hrml = calling();
只要我们在这里,我们就可以编写一个更好的循环来打印向量的内容:
for(size_t i = 0; i < hrml.size(); i++) {
std::cout << hrml[i] << std::endl;
}
或者,如果我们使用 C++11:
for(std::string const& line : hrml) {
std::cout << line << std::endl;
}
而且,如果允许您更改输入文件的格式,我们可以一开始就放弃读取数字,从而生成更小且更易于调试的程序:
#include<iostream>
#include<string>
#include<vector>
std::vector<std::string> calling(){
std::vector<std::string> file;
std::string line;
while(std::getline(std::cin, line)) {
file.push_back(std::move(line));
}
return file;
}
int main() {
std::vector<std::string> hrml = calling();
for(std::string const& line : hrml) {
std::cout << line << std::endl;
}
return 0;
}