Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

c++ - std::cout not printing the value with out endl (newline specifier)

Below is my c++ program to multiply two strings (Integers in strings) and produce the integer result in string. I believe it is due to cout flush problem. Can someone explain how to print the value without endl or any text string just before printing the answer.

 #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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should notice that std::endl includes flushing the output stream. As from the reference documentation:

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

So if you flush cout after printing in your example

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

you would see the result printed Live Demo.

For more information about flushing and what it actually means for buffered output read here please std::ostream::flush().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...