-1

Using the following code in 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;
}

I am outputted with messageBuffer equal to "{[Cam]}\nHello!\n". What I want to happen is messageBuffer to be set to "{[Cam]}Hello!\n". The message inputted can be more than one line long.

Example message input could be:

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

messageBuffer should then be:

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

In actuality I get:

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

Where does this mystery "\n" come from?!

1 Answers1

0

This is because you have to flush your stdin buffer before starting to read the messages (you have some unflushed characters which cause getline() to read it and apped \\n to the message string).

In your case I would advice to do it that way:

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

while(getline(cin,line))
  if(line == "!!")
     break;
  message = message + line + "\\n";
}
syntagma
  • 20,485
  • 13
  • 66
  • 121