简体   繁体   English

读取多行文本直到空白行

[英]reading multiple lines of text until blank line

I'm working on a program that gets the user to enter text until the program reads a blank line. 我正在开发一个程序,让用户输入文本,直到程序读取空白行。 So far, I have this: 到目前为止,我有这个:

#include <iostream>
#include <cstring>

int main() {
    string text; 
    cout << "Enter Your Text: " << endl; 
    getline(cin,text);
    cout << "Text" << endl;
    return 0;
}

But, this only outputs my text as a line and not individual lines, like I would like it to. 但是,这只会将我的文本输出为一行而不是单独的行,就像我希望的那样。 And then there is the part when it reads a blank line that signifies the end of the user input. 然后有一个部分,当它读取一个表示用户输入结束的空白行。

I read that getline() gets all user input, but how do I display it as individual lines? 我读到getline()获取所有用户输入,但是如何将其显示为单独的行?

I read that I may have to use a tokenizer, but I am confused as to how they work, and how you actually write one. 我读到我可能不得不使用一个标记器,但我对它们如何工作以及你是如何编写标记器感到困惑。 I was thinking of using a vector, or some kind of array, but vectors are the only ones I am sort of familiar with. 我正在考虑使用矢量或某种数组,但矢量是我唯一熟悉的数据。

And I'm not quite sure how to get the program to stop at a blank line. 而且我不太确定如何让程序停在空白处。 I was thinking maybe a while loop, but what would go in the parenthesis, and how would that be combined with getting the user input? 我想的可能是一个while循环,但是括号中会有什么,以及如何与获取用户输入相结合?

What I'm basically trying to figure out is how to modify my code to output the user input as lines rather than one whole statement, and to stop getting user input when the user enters a blank line. 我基本上想弄清楚的是如何修改我的代码以将用户输入输出为行而不是整个语句,并在用户输入空行时停止获取用户输入。

Try something like this: 尝试这样的事情:

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

int main()
{
    std::vector<std::string> text; 
    std::string line; 

    std::cout << "Enter Your Text: " << std::endl; 

    while (std::getline(std::cin, line) && !line.empty())
        text.push_back(line); 

    std::cout << "You entered: " << std::endl; 

    for (auto &s : text)
        std::cout << s << std::endl;

    return 0;
}

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

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