【问题标题】:C++ multiple line input from keyboard从键盘输入 C++ 多行
【发布时间】:2014-12-22 04:06:54
【问题描述】:

对于我的一个任务,我们假设从键盘接收几行输入。例如:

请输入您的姓名:(这是静态的。始终输入 1 个) 贾斯汀

请输入名称:(可以是任意数量的输入,最小为 1) 乔
鲍勃
约翰
杰克逊

最后,我想将开头输入的名称与后面输入的所有名称进行比较。我尝试使用 getline 和 cin,但这似乎只有在我知道我希望输入的姓名的确切数量时才有效。谁能指导我正确的方向。谢谢

【问题讨论】:

    标签: c++ string input cin getline


    【解决方案1】:

    试试这个

    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;
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您应该添加一些粗略的代码来显示您在完成作业时所做的努力。 不过,我会为你提供一些初始的naive代码(请阅读里面的cmets!):

      #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
      }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多