简体   繁体   English

C ++ std :: cout和字符串打印顺序错误

[英]C++ std::cout and string printing in wrong order

I have a simple program running on Linux using g++ compiler: 我有一个使用g ++编译器在Linux上运行的简单程序:

#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 . 编译: g++ -o test test.cpp When I run this, the fullstop is printed BEFORE the string s, not after. 当我运行此命令时,句号是在字符串s之前而不是之后打印的。 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
}

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

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