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

时间:2013-07-08 23:08:35

标签: c++ g++

我使用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;

}

编译:{{1​​}}。当我运行它时,在字符串s之前打印fullstop,而不是之后。有人知道为什么会这样吗?是否容易修理?

感谢。

1 个答案:

答案 0 :(得分:6)

如果字符串末尾有回车符,则会在打印时将输出位置移动到控制台行的开头。

#include <iostream>

int main()
{
    std::cout << "some line\r" << "." << std::endl;
    //                     ^^ carriage return
}
相关问题