gpt4 book ai didi

c++ - 为什么 vector.size() 一行读得太少了?

转载 作者:行者123 更新时间:2023-11-30 03:11:01 26 4
gpt4 key购买 nike

运行以下代码时,读取的行数将少于实际行数(如果输入文件本身是 main 文件,否则)这是为什么?我该如何改变这个事实(除了只加 1)?

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
// open text file for input
string file_name;

cout << "please enter file name: ";
cin >> file_name;

// associate the input file stream with a text file
ifstream infile(file_name.c_str());

// error checking for a valid filename
if ( !infile ) {
cerr << "Unable to open file "
<< file_name << " -- quitting!\n";
return( -1 );
}
else cout << "\n";

// some data structures to perform the function
vector<string> lines_of_text;
string textline;

// read in text file, line by line
while (getline( infile, textline, '\n' )) {
// add the new element to the vector
lines_of_text.push_back( textline );

// print the 'back' vector element - see the STL documentation
cout << "line read: " << lines_of_text.back() << "\n";
}
cout<<lines_of_text.size();
return 0;
}

最佳答案

您的代码是正确的。这是一个可能有帮助的小测试用例:

void read_lines(std::istream& input) {
using namespace std;
vector<string> lines;
for (string line; getline(input, line);) {
lines.push_back(line);
cout << "read: " << lines.back() << '\n';
}
cout << "size: " << lines.size() << '\n';
}

int main() {
{
std::istringstream ss ("abc\n\n");
read_lines(ss);
}
std::cout << "---\n";
{
std::istringstream ss ("abc\n123\n");
read_lines(ss);
}
std::cout << "---\n";
{
std::istringstream ss ("abc\n123"); // last line missing newline
read_lines(ss);
}
return 0;
}

输出:

read: abc
read:
size: 2
---
read: abc
read: 123
size: 2
---
read: abc
read: 123
size: 2

关于c++ - 为什么 vector.size() 一行读得太少了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2694642/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com