键盘上的C++多行输入

C++ multiple line input from keyboard

本文关键字:输入 C++ 键盘      更新时间:2023-10-16

对于我的赋值,我们假设从键盘输入几行。例如:

请输入您的姓名:(这是静态的。总是1个输入)Justin

请输入名称:(可以是任意数量的输入,最小为1)乔
Bob
约翰
Jackson

最后,我想将开头输入的名称与后面输入的所有名称进行比较。我尝试过使用getline和cin,但这似乎只有在我知道要输入的确切名称数量的情况下才有效。有人能指引我朝正确的方向走吗。感谢

试试这个

void read_lines( std::istream& in, std::list< std::string >& list ) {
    while( true ) {
        std::string line = "";
        std::getline( in, line );
        if( line != "" ) {
            list.push_back( line );
        } else {
            break;
        }
    }
}

您应该添加一些粗略的代码来显示您在完成任务方面所做的努力。然而,我将为您提供一些初始的天真代码(请阅读里面的评论!):

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
    string name, temp;
    vector<string> names; // this is just one of the possible container that you can use
    bool result = false; // flag used to store the result of the matching operation (default: false)
    // first we ask the user to enter his/her name
    cout << "Please enter your name:" <<endl;
    cin >> name;
    // then we need something a little bit more complicated to look for variable number of names
    cout << "Please enter the names:" <<endl;
    while(cin)
    {
        cin >> temp;
        names.push_back(temp);
    }
    // This for-loop is used to go through all the input names for good-match with the user name
    for( int i = 0; i < names.size(); i++ )
    {
        temp = names.front();
        if (name == temp) result = true; // change the flag variable only in case of match
    }
    cout << "Valid match: " << (result?"yes":"no"); // ternary operator
}

你在问题中没有提供足够的细节。。所以上面的代码可能不完全符合您的要求!