简体   繁体   English

我的 cout 有什么问题?

[英]What wrong with my cout?

In C++, Ubunt 12.04, I have a file named config.txt which contains user name and password .在 C++、Ubunt 12.04 中,我有一个名为config.txt的文件,其中包含user namepassword I have 2 public static string variables: USER and PASSWORD .我有 2 个public static string变量: USERPASSWORD This is my code:这是我的代码:

// Read file from config
string text[2];
int count = 0;
while(!fin.eof()){
    getline(fin,text[count]);
    count++;
    if(count == 2){
        break;
    }
}
CONNECTOR::USER = text[0];
CONNECTOR::PASSWORD = text[1];

string userAndPassword =  CONNECTOR::USER + ":" + CONNECTOR::PASSWORD;
cout << CONNECTOR::USER << endl; // It's fine, right user: qsleader
cout << CONNECTOR::PASSWORD << endl; // ok, right password: 123456
cout <<"user and password: " <<  userAndPassword << endl; // It's weird text! Problem here!

The weird text result is: :123456d password: qsleader !!奇怪的文本结果是:123456d password: qsleader !! This is not what I expected!这不是我所期望的! But I don't know why this happen?但是不知道为什么会这样? Can anyone give me an suggestion?谁能给我一个建议? (If i print: cout << "user and password: qsleader:123456" , the result is good!!)! (如果我打印: cout << "user and password: qsleader:123456" ,结果很好!!)!

The problem is created when you read the values.读取值时会产生问题。 Indeed, I guess that your file has the two items on two different lines.事实上,我猜你的文件在两个不同的行上有两个项目。 Furthermore, I guess this file uses Windows line endings.此外,我猜这个文件使用 Windows 行结尾。 Therefore, when you read the first item, it reads qsleader\\r and then stops as the next extracted character is \\n , extracted but not appended to the string.因此,当您阅读第一项时,它会读取qsleader\\r ,然后在下一个提取的字符是\\n停止,提取但未附加到字符串。

When you create the userAndPassword string, it is in fact qsleader\\r:123456 .当您创建userAndPassword字符串时,它实际上是qsleader\\r:123456 This special character \\r is a return carriage.这个特殊字符\\r是回车。 It makes the cursor go to the beginning of the line.它使光标移动到行首。 Therefore, on the last line, you first output user and password: qsleader , then go back to the first column, and write :123456 , resulting in :123456d password: qsleader .因此,在最后一行,您首先输出user and password: qsleader ,然后返回第一列,并写入:123456 ,从而得到:123456d password: qsleader

You are setting userAndPassword to a hellish expression involving assignments.您将userAndPassword设置为涉及赋值的地狱表达式。 I guess your intent was:我猜你的意图是:

string userAndPassword = CONNECTOR::USER + ":" + CONNECTOR::PASSWORD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM