c++ - std::cout not printing the value with out endl (newline specifier) -
below c++ program multiply 2 strings (integers in strings) , produce integer result in string. believe due cout flush problem. can explain how print value without endl or text string before printing 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]; (int = m - 1; >= 0; i--) { (int j = n - 1; j >= 0; j--) { res[m + n - - j - 2] += (s1[i] - '0') * (s2[j] - '0'); res[m + n - - j - 1] += res[m + n - - j - 2] / 10; res[m + n - - j - 2] %= 10; } } (int = m + n - 1; >= 0; i--) { if (res[i] != 0) { (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!! prints "0" correctly **/ return 0; }
you should notice std::endl
includes flushing output stream. reference documentation:
inserts newline character output sequence
os
, flushes if callingos.put(os.widen('\n'))
followedos.flush()
.
so if flush cout
after printing in example
cout << multiply("0", "0"); cout.put(cout.widen('\n')); cout.flush();
you see result printed live demo.
for more information flushing , means buffered output read here please std::ostream::flush()
.
Comments
Post a Comment