简体   繁体   中英

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

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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