c++ - 如何使用户输入多行

标签 c++ loops input cin getline

我想使用户能够输入多行字符串。我一直在尝试for循环,但到目前为止,仅返回最后一行。

例如,用户输入以下字符串和行。string str;getline(cin, str);
或循环for(i=0;i<n;i++){getline(cin, str);}
这些是用户输入的输入

Basketball Baseball Football //line 1

Hockey Soccer Boxing" //line 2



现在,我希望能够一次返回这两行。我不知道该怎么做。
另外,我发现更困难的是试图弄清楚用户是否只能输入一行,两行或三行。我知道如何用cases来点缀帽子,但是我现在想知道是否有一种更简单的方法,看起来并不那么困惑,

最佳答案

为什么不在while循环中使用std::getline,所以一旦输入空行,循环就会退出,如下所示:

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

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

    while (getline(std::cin, line) && !line.empty()) {
        lines.push_back(line);
    }

    std::cout << "User has entered " << lines.size() << " lines" << std::endl;
    for (auto const& l : lines) {
        std::cout << l << std::endl;
    }

    std::cout << "... End of program ..." << std::endl;
    return 0;
}

您可以存储用户输入到 std::vector 容器中的每个行,并在以后再次检索这些行。

可能的输出:
First line
Second line

User has entered 2 lines
First line
Second line
... End of program ...

更新

如果要允许用户仅输入2行,并且要使用for循环,则可以执行以下操作:

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

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

    for (int i = 0; i < 2; i++) {
        std::getline(std::cin, line);
        lines.push_back(line);
    }

    std::cout << "User has entered " << lines.size() << " lines" << std::endl;
    for (auto const& l : lines) {
        std::cout << l << std::endl;
    }

    std::cout << "... End of program ..." << std::endl;
    return 0;
}

输出可能是:
First line                                                                                                                                                                         
Second line                                                                                                                                                                        
User has entered 2 lines                                                                                                                                                           
First line                                                                                                                                                                         
Second line                                                                                                                                                                        
... End of program ...

关于c++ - 如何使用户输入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60159257/

相关文章:

C++ IMG_LoadTexture() 返回 null

调用 delete [] 时出现 C++ HEAP 错误

c++ - 虚拟基类析构函数调用顺序?

javascript - 检查 JS 对象中是否存在数组元素的更好方法?

Java读取多行后打印多行

c++ - 将数组传递给函数错误

java - 如何从方法中重新启动程序

Matlab 使用日期向量对日期和时间序列进行向量化实现

javascript - 输入值等于/匹配带有字符串的声明数组中的任何值

c# - input submit 有两种类型的值