Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code blocks MinGW and the %n conversion character

I am trying to use a conversion character to count the number of chars printed so far with the following code.

#include <stdio.h>
int main(void) {
    int n;
    printf("%s: %nFoo\n", "hello", &n);
    printf("%*sBar\n", n, "");
}

When working correctly this code prints Hello Foo, then on the next line Bar is aligned with Foo.

This works fine when compiled with GCC on my linux box. However, when compiled using minGW in code blocks on my Windows PC %n does not work, and all that is printed is hello: Bar all on one line. Why so and can I fix this?

like image 478
Andrew S Avatar asked Jan 18 '14 03:01

Andrew S


People also ask

Does CodeBlocks use Mingw?

CodeBlocks is an open-source, cross-platform (Windows, Linux, MacOS), and free C/C++ IDE . It supports many compilers, such as GNU GCC (MinGW and Cygwin) and MS Visual C++. It supports interactive debugging (via GNU GDB or MS CDB).

How do I link CodeBlocks with Mingw?

You need to setup the MinGW 8.1. 0 in CodeBlocks. The steps are: Settings -> Compiler -> GNU GCC Compiler -> Toolchain executables -> path\to\mingw64 (without bin). Then confirm.

How do you display output in CodeBlocks?

go to view -> perspective -> and enable code::Blocks default, you can see your projects left side and down the build logs and messages etc. Show activity on this post.

Can we use CodeBlocks for HTML?

Code::Blocks provides an 'Embedded HTML Viewer', which can be used to display simple html file and find keywords within this file.


2 Answers

use compile option -D__USE_MINGW_ANSI_STDIO

E.g

>gcc prog.c -D__USE_MINGW_ANSI_STDIO

or

>clang prog.c -D__USE_MINGW_ANSI_STDIO

Another solution is placing this command above the first import statement like so (see below). This will ensure that the ANSI I/O standards are preferred over Microsoft's. More information in this link here.

#define __USE_MINGW_ANSI_STDIO 1
#include <stdio.h>
like image 134
BLUEPIXY Avatar answered Sep 30 '22 07:09

BLUEPIXY


It looks like this is a Windows issue, this article says:

The default C-RunTime Library (msvcrt.dll) on Vista seems to have %n disabled by default - security reasons of course

It looks like there is a _set_printf_count_output to enable it.

BLUEPIXY found that in order to get it working outside Visual Studio you need to define __USE_MINGW_ANSI_STDIO:

#define __USE_MINGW_ANSI_STDIO 1
like image 20
Shafik Yaghmour Avatar answered Sep 30 '22 09:09

Shafik Yaghmour