Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::cout and string printing in wrong order

Tags:

c++

g++

I have a simple program running on Linux using g++ compiler:

#include <string>
#include <sstream>
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char **argv){
 fstream file;
 string s;
 file.open("sample/dates.dat", fstream::in);
 if(!file.good())
  return 0;
 getline(file, s);
 cout << s << "." << endl;
 return 0;

}

Compiled with: g++ -o test test.cpp. When I run this, the fullstop is printed BEFORE the string s, not after. Does anybody know why this is happening? And is it easy to fix?

Thanks.

like image 350
Toby Avatar asked Oct 26 '25 09:10

Toby


1 Answers

If there is a carriage return at the end of the string it will move the position of output to the beginning of the console line when printed.

#include <iostream>

int main()
{
    std::cout << "some line\r" << "." << std::endl;
    //                     ^^ carriage return
}
like image 63
Captain Obvlious Avatar answered Oct 28 '25 21:10

Captain Obvlious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!