在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”来自哪里?!
答案 0 :(得分:0)
这是因为你必须在开始阅读消息之前刷新stdin
缓冲区(你有一些未刷新的字符导致getline()
读取它并且\\n
apped message
到cin.clear();
cin.ignore(INT_MAX,'\n');
while(getline(cin,line))
if(line == "!!")
break;
message = message + line + "\\n";
}
1}}字符串)。
在你的情况下,我会建议这样做:
if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
alreadyChoosen += rand + ",";
elements.eq(rand).show();
++i;
}