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

标签 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;

}

编译:g++ -o test test.cpp。当我运行它时,句号打印在字符串 s 之前,而不是之后。有人知道为什么会这样吗?修复起来容易吗?

谢谢。

最佳答案

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

#include <iostream>

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

关于C++ std::cout 和字符串打印顺序错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17537456/

相关文章:

C++ 跳过代码行?

c++ - 在 Allegro 5 的运行时更改基元的颜色

c++ - 如果 SDL_BlitSurface 中的 src 和 dest 相同会发生什么?

c++ - CUDA 线程 ID

c++ - 用于多级指针取消引用?

c++ - 错误 : nested class in a nested class in a template class "is not a type"

c++ - GCC 7.3 是否省略了引用返回成员函数的 [[nodiscard]] 属性?

c++ - 为什么在不返回值的情况下流出非 void 函数的末尾不会产生编译器错误?

c++ - G++ 警告 : built for unsupported file format which is not the architecture being linked

c++ - 分发 C++ 类的最佳方法是什么