【问题标题】:std::cout not printing the value with out endl (newline specifier)std::cout 不打印没有 endl 的值(换行符)
【发布时间】:2016-02-07 20:28:26
【问题描述】:

下面是我的 c++ 程序,用于将两个字符串(字符串中的整数)相乘并在字符串中生成整数结果。我相信这是由于 cout flush 问题。有人可以在打印答案之前解释如何在没有 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;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

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

    在输出序列os 中插入一个换行符并刷新它,就像调用os.put(os.widen('\n')) 后跟os.flush() 一样。

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

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

    您会看到打印的结果 Live Demo

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

    【讨论】:

    • 嗨..我试过你的建议在打印后刷新 cout.. 但它仍然不起作用。 cout
    • @sureshrmdec 抱歉,我已将我的答案更新为文档中确切指定的内容,现在可以使用了。
    猜你喜欢
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2013-01-29
    • 2017-05-13
    • 2020-03-19
    • 1970-01-01
    相关资源
    最近更新 更多