Printf doesnt pop - c++

I'm new to programming in c++ and I'm facing a problem following lynda.com tutorials. It seems okay on the tutorial video but this isnt working with me.
#include <stdio.h>
enum { max_string = 127 };
static char string[max_string + 1 ] = "";
int main( int argc, char ** argv ) {
printf("Type a string: ");
fgets(string, max_string, stdin);
printf("The string is %s", string);
return 0;
}
And when I run this something blank appears and I need when I right something like "hey" in the blanket space, this happens:
hey
Type a string: The string is hey
This is completely strange for me and I have no idea what Im doing wrong tbh.
I'm using Eclipse btw.
Could someone help me out?

It appears that your standard output stream is line-buffered, meaning that text you print doesn't appear until you've printed a complete line. It should be unbuffered if you're writing to an interactive device; perhaps something is preventing the system from being aware that the output device is interactive.
Adding
fflush(stdout);
after your first printf should force the "Type a string: " prompt to appear immediately (and even if your output is unbuffered, fflush(stdout) is harmless).
I was about to suggest changing your second printf from:
printf("The string is %s", string);
to:
printf("The string is %s\n", string);
to ensure that your program's output ends with a newline (some systems can misbehave if it isn't) -- but fgets() actually leaves the newline in your string (unless the input line was very long). Eventually you'll want to be able to deal with that kind of thing.

Related

Replacements for deprecated strcpy/strcat when using char*

I have code for a 'zombie translator' as an example from my professor. From what I can tell it takes a string of english words and applies a few rules to it via functions. It currently uses strcpy and strcat to do this, however it will not compile even if I change them to strcpy_s. Without including the other functions (for the sake of space), here is my main function as an example
int main()
{
char english[MAX];
char zombie[MAX];
char zombie_word[MAX];
int pos_e; /* Current position in english line of text */
int pos_z; /* Current position in line of translated zombie text */
while (1) {
pos_e = 0;
pos_z = 0;
strcpy(zombie, "");
cout << ("Enter English text: ");
cin >> english;
/* This loop translates the line from english to zombie. */
do
{
get_next_word(english, &pos_e, zombie, &pos_z);
translate_word(english, &pos_e, zombie_word, &pos_z);
strcat(zombie, zombie_word);
} while (pos_e < strlen(english));
print_translation(zombie);
}
return 0;
}
So more specifically, what should i do to the line strcat(zombie, zombie_word); to make it compile properly in Visual Studio 2015?
It's not for a grade, I just really want to be able to understand this before the midterm, and it's a bit difficult to play around with it. I would prefer not to have to disable it through _CRT_SECURE_NO_WARNINGS so that I know what to do if I need to do something similar.
Perhaps changing the char variables into strings or something like that? I've been looking around for awhile and can't find the actual process.
Thank you very much for any assistance, I greatly appreciate your time.
From Microsoft: strncat_s
You need to include the length of the array to prevent buffer overflow dangers.
The API is:
errno_t strncat_s(
char *strDest,
size_t numberOfElements,
const char *strSource,
size_t count
);
numberOfElements is size of destination array.

no output in console window:codeblocks

Heya I have installed codeblocks..on windows7
codeblocks-13.12mingw-setup-TDM-GCC-481.exe
my program is building but after executing i am getting a console window only with a cursor and no output. I tried it with many other programs but the same thing is happening.
I have also set all the settings to default and have also re installed codeblocks.
I am attaching snippet of the console window for the program code:
#include <stdio.h>
int main()
{
printf("helloworld%s")
return 0;
}
Even the default program was not working because it failed to recognize iostream.
PLease help..!
You forgot the ; at the end of the printf() line, you should have a syntax error when compiling.
The %s doesn't mean any sense if there is no additionnal argument. It is used when you want to print a string stored in a variable. Example:
int main(int argc, char** argv) {
char str[] = "world!";
printf("Hello %s\n", str);
}
will print "Hello world!".
Unless you know what you're doing, you should add a \n at the end of the printed line (before output on stdout are buffered, and printed when the buffer is full : Is stdout line buffered, unbuffered or indeterminate by default?)

fprintf() / std::cout doesn't print part of the string to stdout/stderr

I have this strange problem with stdout/stderr.
I want to apologize for not being able to put here the original code, it's too long / too many libraries dependent etc...
So please let me know if you ever encountered anything like it, or what may cause this issue without getting the original code, only the idea and examples of the simple things I tried to do:
I'm using g++ (GCC) 4.4.6 20120305 (Red Hat 4.4.6-4) on RHEL 6.3
I couldn't isolate the problem for putting it here, I'll give code examples of what I did.
fprintf() / printf() / std::cout stops working after a while.
I'm using boost::asio::io_service with deadline_timer in order to call a my_print() function.
This my_print() function prints to screen every 1 second some information.
In order to print, I use alignments, like the following:
fprintf(stdout, "%*s\n", -printWidth, someEnumToStr[i]);
fprintf(stdout, "%s\n", aString);
fprintf(stdout, "%u\n", num);
While aString is a std::string. Sometimes I construct aString from std::ostringstream.
Sometimes I construct it with snprintf().
I have an std::map with information, exactly 16 elements inside the map. I iterate over it, and for each element I try to print data with the example of fprintf() above.
For an unknown reason, the line of element 16 isn't printed.
If I call the executable, and redirect stdout to a file (./a.out > aaa.txt) the line of element 16 is getting printed.
If I open a new FILE* and fprintf() to this file, again, everything is getting printed (all lines, including line of element 16)
Before using fprintf() I tried to use std::cout (and alignments with std::cout.width(printWidth) << std::left...), The same behavior happened, but when line 16 wasn't drawn, stdout got stuck (I mean, the program still worked, but nothing was printed to stdout never again. I had to call std::cout.clear() for it to work again). Since a point in the code, which I couldn't lay my hands on, std::cout.failbit and badbit were 1.
If I run the code with valgrind this behavior doesn't happen. valgrind doesn't say anything wrong.
If I run it with gdb it happens, but gdb doesn't say anything wrong.
If I run it in an IDE (clion) in debug mode, it doesn't happen.
If I run it in IDE, without debug, it happens.
I figure it depends on the printWidth I give for the alignment in fprintf() - When printWidth is bigger, it happens sooner (when it's smaller, line 16 is randomly getting printed).
Another important thing: it happens more frequently when there is more to print.
I tried to give std::cout a bigger buffer (not his default) and it didn't work.
I tried to buffer all of the output into a buffer (instead of printing each line), then to only fprintf() once. Same behavior happens.
I didn't find anywhere in the code I try to print a NULL pointer.
I print with \n every couple of fprintf()s, and do fflush() in the end of my_print()
Please let me know if you know anything.
Illustration:
deadline_timer..... every 1 sec... my_print()
boost::asio::io_service.run
my_print() {
for(std::map<>::iterator... begin, end, ++it....) {
fprintf()s....
}
}
Non printable characters may be breaking terminal.
fprintf(stdout,"%s", astdstring.cstr() );
Is how to print std::string
I use boost::asio, I have a callback to read from stdin. this read is nonblocking - happens with async_read_some().
The problem was stdin was turned to be nonblocking, and it also caused stdout to be nonblocking as well because they point to the same file description (explanation).
It caused the fprintf() calls to fail (returned -1 with errno 11) and not all of the output got printed out on the screen.
It has no relation to boost.
I succeeded isolating the problem, the following code creates this problem:
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[]) {
const int problem = 8000;
const int myBuffSize = 32000;
char *myBuff = new char[myBuffSize];
int myoffset = 0;
memset(myBuff, '-', myBuffSize);
int flags;
bool toogle = true;
bool running = true;
// Comment from here
if ((flags = fcntl(STDIN_FILENO, F_GETFL, 0)) < 0) {
printf("error fcntl()\n");
return 0;
}
if (fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK) < 0) {
printf("error fcntl()\n");
return 0;
}
// Comment until here
while(running) {
toogle = toogle ? false : true;
if (toogle) {
snprintf(myBuff + problem, myBuffSize - problem, "fin\n\n");
} else {
snprintf(myBuff + problem, myBuffSize - problem, "end\n\n");
}
fprintf(stdout, "%s", myBuff);
sleep(1);
}
delete[] myBuff;
return 0;
}
If you'll comment the // Comment from here to // Comment untill here, it will print all of the output (fin and end will be printed).
One solution to this problem is to open another fd to the current tty using fopen(ttyname(STDOUT_FILENO), "w") and to print into it.
I believe another solution is to async_write() into screen.
The output might be stuck in a buffer, and not flushed before program termination.
Try adding exit(0) at the end of the program, and see if it helps.
http://www.cplusplus.com/reference/cstdlib/exit/
All C streams (open with functions in <cstdio>) are closed (and flushed, if buffered), and all files created with tmpfile are removed.

C/C++ : Can I keep the cursor in the current line after pressing ENTER?

I would like to ask if there's any way to keep the cursor in the current line after pressing ENTER !!
for example ...
#include<stdio.h>
int main()
{
int d=0;
printf("Enter a number : ");
scanf("%d",&d);
if(d%2)printf(" is a Odd number\n");
else printf(" is a Even number\n");
return 0;
}
An example of output :
Enter a number : 10
is a Even number
... but what I need is something like that :
Enter a number : 10 is a Even number
I want to put "is a Even number" (or " is a Odd number") next to the number entered by user
The user is pressing enter, and this is being echoed back and starting a new line.
In order to avoid this, you'll need to turn off echo (and then read and echo individual characters except for newline). This is system-dependent, for example on Linux you can put the tty into raw/uncooked mode.
You may find a library such as GNU readline that does most of the work for you.
The simple answer is "you can't". There is no standard C++ functions to control this behaviour, or to read data without hitting enter at the end (in fact, the data hasn't really been "entered" until you hit enter, so the program won't see the data).
You can use non-standard functionality, such as additional libraries, such as a "curses" library or system dependent code, but we would then have to produce the code to read characters one at a time and merge it together using code that you write.
I would suggest that you use the "repeat the input in the output", and simply do something like this:
printf("%d is", d);
if (d%2)
printf("an odd number\n");
else
printf("an even number\n");
Set up raw keyboard mode and disable canonical mode.
That's almost, how linux manages not to show password chars in terminal.
Termio struct is the thing you should google for.
One link is :
http://asm.sourceforge.net/articles/rawkb.html
The Constants of the assembly are also available for a syscall ioctl.
This trick may help, if you have a vt100-style terminal: cursor movements.
\033 is ESC, ESC + [ + A is cursor up, ESC + [ + C is cursor right
int main()
{
int d=0;
printf("Enter a number : ");
fflush(stdout);
scanf("%d",&d);
printf("\033[A\033[18C%d is a an %s number\n", d, d%2 ? "odd" : "even");
return 0;
}
not with printf and scanf... have you tried with getc() and ungetc(char) ?
OR, try to play with printf("%c", (char)8); if I remember correctly that's a backspace
otherwise, you'll probably have to use some output lib such as ncurses

C++ Infinite Loop

I'm learning C++.
nav is an integer .
I want to ask user for typing a valid value, if he / she type an invalid value.
void main()
{
printf("Type an integer : ");
if(!scanf("%d", &nav))
{
system("cls");
printf("Invalid ! \n");
main();
}
}
But it's blinking after typing first value . It's blinking like reloading screen. I think it's infinite loop.
How can i do it in right way ? I want to ask a number from users, until it's typing a real number .
If the user types an invalid input, scanf() won't consume it, and you'll be left peeking the same offending input character forever. You need to first read whatever the user enters — I recommend using std::getline() — and then try to parse that with strtol(), sscanf() or std::istringstream. Don't use atoi() because it doesn't report failures.
int nav;
{
string line;
while (getline(cin, line))
if (istringstream(line) >> nav)
break;
}
EDIT: See the comments for a rather beautiful rendition of the above logic. I've left it out of the answer because: a) I don't want to steal someone else's idea, and b) I'm not sure I'd present a newcomer to C++ with that formulation — not in one go, at least.
P.S.: You can't call main() in C++.
Two things.
Scanf needs the 'enter' key pressed before it will process input, so the blinking could just be the cursor waiting for the next key.
Also, calling main from main is fairly non-standard. You should look into a 'while' loop.
Your program is not a good one, but nevertheless I will tell you what is happening.
In C/C++, when scanf cannot read an integer (%d) from input, it wouldn't read anything. That is, whatever prevented scanf from reading an int, will remain there. On the next scanf the same character is going to cause an error.
Let me demonstrate by an example. Imagine you are reading many integers from this input:
12 13 Shahbaz 15
Now if you call scanf with %d, you will read 12 and the input would be:
13 Shahbaz 15
Next, you call scanf with %d and you will read 13. now the input would be:
Shahbaz 15
Again, you call scanf with %d. Here, the input begins with an S (after the whitespace) which makes scanf return with a failure as it could not read an integer. The input is left untouched (save perhaps for the whitespace). That is, the input will be:
Shahbaz 15
As you can see, reading the input with %d will give you the exact same error and you are stuck in an infinite loop.
To solve this, you have many choices. This very much depends on how you want to handle the situation, but two methods would be to either read a character (with %c) or a string (with %s) right after printing printf("Invalid\n").
The first method is good for handling input like this:
12 13 q14 15
where q is a mistake that needs to be ignored. The second method is good for handling input like this:
12 13 Shahbaz 15
where the invalid data are meaningful words, but you just want to ignore them.
And the way I would write it, if I wanted to use scanf would be:
int main() // always write int main
{
int nav;
printf("Type an integer: ");
while (scanf("%d", &nav) != 1) // scanf returns number of successful %'s read
{
printf("Invalid number. Try again: ");
scanf("%*s"); // read a %s but ignore it
}
// The rest of the program, using nav
return 0;
}