简体   繁体   English

2D字符串向量的cout仅打印最后一行

[英]cout for 2D string vector only printing last line

I'm reading a text file and loading to a std::vector<std::string> course and when I attempt to print it based on course.size() and course[i].size it only prints the last line. 我正在读取文本文件并将其加载到std::vector<std::string> course并且当我尝试基于course.size()course[i].size course.size()打印它时,它仅显示最后一行。

Here is the code: 这是代码:

int main(int argc, char** argv) {
    ifstream fin(argv[1]);
    vector<string> course;
    string line;

    while (getline(fin, line)) {
        course.push_back(line);
    }

    for (int i = 0; i < course.size(); i++) {
        for (int j = 0; j < course[i].size(); j++) {
            cout << course[i][j];
        }
    }

    return 0;
}

Tried maybe the '\\r' removal by adding: 尝试通过添加以下内容来删除'\\r'

if (!line.empty() && line[line.size() - 1] == '\r') {
    line.erase(line.size() - 1);
}

But that just printed out each [i][j] per line next to one another. 但这只是将每行[i][j]彼此相邻地打印出来。

Data looks like this: 数据如下所示:

xxxxxxxxxxxx
xxx   yyyxxx
xxxXXYYxxyyy

std::getline does not add the delimiting character (the newline in your case) to the output string. std::getline 分隔字符(在你的情况下,新行)添加到输出字符串。 Thus, none of those std::string of your std::vector<std::string> course contains a newline. 因此,您std::vector<std::string> course的所有std::string都不包含换行符。 Thus you need to output a newline yourself after writing each of those strings. 因此,您需要在编写每个字符串之后自行输出换行符。

Then please note that the inner for loop is completely unnecessary. 然后请注意,完全不需要内部for循环。 There's an overload/specialization of operator<< for std::string , thus you can simplify to: std::string有一个operator<<的重载/专业化,因此您可以简化为:

for (std::size_t i = 0; i < course.size(); ++i) {
  std::cout << course[i] << std::endl; // or '\n' if you don't need flushing
}

If you insist on the inner loop: 如果您坚持内循环:

for (std::size_t i = 0; i < course.size(); i++) {
    for (std::size_t j = 0; j < course[i].size(); j++) {
        std::cout << course[i][j];
    }
    std::cout << '\n';
}

Live in action. 行动起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM