神秘的加法问题

Mysterious addition issue

在 C++ 中使用以下代码:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class User
{
   public:
      User();
      void setName(string username);
      string getName();
   private:
     string name;
};

User::User()
{}

void User::setName(string username)
{
   name = username;
}

string User::getName()
{
   return name;
}

class System
{
   public:
      System();
      void createUser();
      void postMessage();
      string getCurrentUser();
      string messageBuffer;
   private:
      vector<User> users;
      string currentUser;
};

System::System()
{
   messageBuffer = "";
}

void System::createUser()
{
   string username;
   bool userExists = false;

   cout << "Please enter a user name: ";

   cin >> username;   
   cout << endl;

   for(int i = 0; i < users.size(); i++)
   {
      if(users.at(i).getName() == username)
         userExists = true;
   }

   if(!userExists)
   {
      User temp;        //creates a temporary user stored in vector of Users    
      users.push_back(temp);    //puts new User at end of users

      users.back().setName(username);

      currentUser = users.back().getName();
   }

   if(userExists)
      cout << "User already exists." << endl << endl;

}

void System::postMessage()
{
   string line;
   string message;
   cout << "Enter message: ";

   while(getline(cin,line))
   {
      if(line == "!!")
         break;

      message = message + line + "\n";
   }

   messageBuffer = "{[" + currentUser + "::tweet]}" + message + messageBuffer;
   cout << endl;
}

string System::getCurrentUser()
{
   return currentUser;
}

int main()
{
   System system;

   system.createUser();    //create user named Cam

   system.postMessage();   //input message "Hello!"

   cout << system.messageBuffer << endl;

   return 0;
}

我输出的 messageBuffer 等于“{[Cam]}\nHello!\n”。我想要发生的是将 messageBuffer 设置为“{[Cam]}Hello!\n”。输入的信息可以超过一行。

示例消息输入可以是:

Hello!
How are you all?
I am great!
!!

messageBuffer 应该是:

    "{[Cam]}Hello!\nHow are you all?\nI am great!\n"

实际上我得到:

    "{[Cam]}\nHello!\nHow are you all?\nI am great!\n"

这个神秘的“\n”从何而来?!

这是因为您必须在开始阅读消息之前刷新 stdin 缓冲区(您有一些未刷新的字符导致 getline() 读取它并将 \n 应用到message 字符串).

对于你的情况,我建议这样做:

cin.clear();
cin.ignore(INT_MAX,'\n'); 

while(getline(cin,line))
  if(line == "!!")
     break;
  message = message + line + "\n";
}