Question:
[C++] (Ubuntu) This code is malfunctioning!?
Anonymous
2013-03-20 12:56:19 UTC
include
#include
#include
#include
#include

using namespace std;

void type(char[]);

int main(){

type("Testing typewriter effect");

cout << "code after typewriter completed" << endl;

return 0;
}

void type(char st[]){
cout << "code right after type function completed" << endl;

for(unsigned int x = 0; x < strlen(st); x++){
cout << st[x];
srand(time(0));
int r = rand() % 55 + 30;
cout << "\n"; //it just won't work unless I put this line with \n , any other cout won't work
usleep(150*1000);
}
}
Five answers:
?
2013-03-20 18:03:27 UTC
standard output is buffered. It will not be displayed until you issue a flush command, by executing cout.flush() or cout << flush, which can be combined with endline with cout << endl.

(flush of cout also occurs on any input from cin, on output to cerr, on program termination, and when cout's internal buffer is full)



On Linux, printing \n also flushes the output, but that is not portable. If you want something to appear before a sleep, make sure to flush: http://en.cppreference.com/w/cpp/io/manip/flush or endl: http://en.cppreference.com/w/cpp/io/manip/endl
anonymous
2013-03-20 13:28:39 UTC
I don't have a compiler and I am not on ubuntu at the moment...but the first thing that comes to mind when you say it doesn't work without the newline is that it has something to do with the previous cout statement.



Anyway, are you getting any compiler errors? I only ask because you are passing a string literal of unknown length to a character array that already has a limit (which is determined at compile time).



Try passing the function a CHARACTER pointer, then actually using malloc (or new...since this is C++) and see if that fixes your issue.



I think the issue might be that the string is just never properly terminated, so...it relies on that newline to actually terminate the string.
Jacob
2013-03-20 13:34:04 UTC
I have this problem too, it seems that in ubuntu the output will be one line down sometimes, just add "<< endl" to the back of your last cout and it should work fine.
marlene
2016-12-14 14:19:47 UTC
in contrast to homestead windows international, in unix whilst a c application is compiled it creates a document with call a.out which would be completed. we could have execuable document with distinctive call additionally. no go with of extension EXE
anonymous
2013-03-20 13:26:56 UTC
are you making you program sleep for 150 seconds in your loop?


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...