c++ - std::cout 不打印带有 out endl (换行符说明符)的值

标签 c++

下面是我的 C++ 程序,用于将两个字符串(字符串中的整数)相乘并在字符串中生成整数结果。我相信这是由于 cout 刷新问题造成的。有人可以解释一下如何在打印答案之前打印没有 endl 或任何文本字符串的值。

 #include <iostream>
 using namespace std;
 string multiply (string s1, string s2)
 {
    char str[10];
    string ans="";
    int m=s1.length();
    int n=s2.length();

    if (!s1.compare("0") || !s2.compare("0"))
         return "0";

       int *res = new int[m + n];

       for (int i = m - 1; i >= 0; i--)
       {
         for (int j = n - 1; j >= 0; j--)
         {
          res[m + n - i - j - 2] += (s1[i] - '0') * (s2[j] - '0');
          res[m + n - i - j - 1] += res[m + n - i - j - 2] / 10;
          res[m + n - i - j - 2] %= 10;
         }
       }


       for (int i = m + n - 1; i >= 0; i--)
       {
            if (res[i] != 0) 
            {
                for (int j = i; j >= 0; j--) 
                {
                  sprintf(str,"%d", res[j]);
                  ans+=str;
                }
                return ans;
            }

        }
 }

int main() {

 cout << multiply("0", "0"); // Doesn't work - prints nothing.
 /**cout << multiply("0", "0") << endl; //works!! This prints "0" correctly **/

 return 0;
}

最佳答案

您应该注意到 std::endl 包括刷新输出流。从 reference documentation :

Inserts a newline character into the output sequence os and flushes it as if by calling os.put(os.widen('\n')) followed by os.flush().

因此,如果您在示例中打印后刷新cout

cout << multiply("0", "0");
cout.put(cout.widen('\n'));
cout.flush();

你会看到打印的结果 Live Demo

有关刷新的更多信息及其对缓冲输出的实际含义,请阅读此处 std::ostream::flush() .

关于c++ - std::cout 不打印带有 out endl (换行符说明符)的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35258696/

相关文章:

c++ - 如何在托管类中使用非托管类?

c++ - 三维数组的下标是否严格定义?

c++ - 保留基本功能的重载赋值运算符

c++ - 如何修复 "error: no previous declaration for void awn::vala_array_destroy"?

c++ - 我可以使用多态性将不同的对象存储在 C++ 的数组中吗?

c++ - asio::io_service 工作立即结束

c++ - 如何在 C++ while 循环中创建一个自动递增数组?

C++ Stack 实现意外输出

c++ - DBGHelp.dll 导致在调试版本中加载 msvcrt.dll

c++ - std::string 赋值时出现段错误