Reputation: 8190
In C++, Ubunt 12.04, I have a file named config.txt
which contains user name
and password
. I have 2 public static string
variables: USER
and PASSWORD
. 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
!! 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!!)!
Upvotes: 1
Views: 163
Reputation: 37427
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. 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.
When you create the userAndPassword
string, it is in fact qsleader\r:123456
. This special character \r
is a return carriage. 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
.
Upvotes: 2
Reputation: 171107
You are setting userAndPassword
to a hellish expression involving assignments. I guess your intent was:
string userAndPassword = CONNECTOR::USER + ":" + CONNECTOR::PASSWORD
Upvotes: 0