Here is my simple c code. Can anyone tell me why it gives me this output?
I am coding on an arch linux 4.15.1-2-ARCH machine with the gcc compiler (version: 7.3.0)
I compile with: gcc --std=c99 -Wall --pedantic client.c -o client
I have the following code:
#include <stdio.h>
int main(void) {
printf("Test.");
return 0;
}
But it get the following Output:
Test.%
I don't know where the % is comming from. Would be great if someone can give me a hint.
Your printf string doesn't contain a newline character. As a result, whatever string your shell normally prints as a prompt will appear immediately after what your program prints.
Running on my machine:
$ ./x1
Test.$
My prompt is "$", so that's what appears after the string
Adding \n, which is the escape sequence for a newline, to your string will make your prompt appear on the following line:
printf("Test.\n");
Output:
$ ./x1
Test.
$
Try:
printf("Test.\n");
The word Test. printed by your program probably joined with the first character of your terminal prompt. Adding a \n will print a new line character, so your terminal prompt will be written on the next line when your program exits.
Related
I need to get this stripped-down C program working on Windows 7 using MSys2's gcc toolchain:
#include <stdio.h>
void wmain(int argc, wchar_t *argv[])
{
for (int i = 1; i < argc; i++)
wprintf(L"%s\n", argv[i]);
}
The code compiles with
gcc -Wall -municode -O2 -march=x86-64 -m64 test.c
but gives me the following output
>> ./a.exe kk лл
k (!)
:?:?
I have the following questions:
What am I doing wrong?
How would I downgrade the compiler to
version, say, 9.x, or 10.1? (I'm under the impression that the very
same program compiled about one year ago used to work correctly)
Edit [1]: Meanwhile I managed to set up a new MSys2 environment using gcc 9.3. The "error" persists, so it's not the compiler.
Edit [2]: "Some programmer dude" (cmp. below) described the "immediate" solution (THX!).
Even for the wide-character wprintf the format %s is for narrow character strings.
You need to use %ls to print wide-character strings:
wprintf(L"%ls\n", argv[i]);
However this might still not be enough, as the actual encoding of the input (including arguments) might not be what's expected. You need to take into account the encoding used by the terminal the program is running in.
There are two programs and they get different results, but I don't understand why.
Here is the first:
int main()
{
printf("12345");
fflush(stdout);
printf("\b\b");
fflush(stdout);
return 0;
}
The result is: 123.
Then the second:
int main()
{
printf("12345");
fflush(stdout);
sleep(1);
printf("\b\b");
fflush(stdout);
return 0;
}
but the result is: 12345.
Why does the sleep call make the second result different when I expect a "123" result?
The code was running in the CLion.
and My OS is macOS, if it matters.
Depending on the Terminal, '\b' might "erase" a character or only move the cursor to the left. To have a foolproof solution, use:
#include <unistd.h>
#include <stdio.h>
int main(void)
{
printf("12345");
fflush(stdout);
sleep(1);
printf("\b\b \b\b");
fflush(stdout);
}
Your code first displays "12345" and then displays "123". Without the sleep, the "12345" is displayed for too little time to be visible. With the sleep, you can see the "12345" for about a second before the "4" and "5" are erased.
With the original code (called bs97, compiled from bs97.c), and with my command line prompt Osiris JL:, I get the output:
Osiris JL: bs97
123Osiris JL:
Note that the new prompt has overwritten the 45. You can see that if you add putchar('\n'); after the second fflush(). (I added void to int main(void) to avoid compilation warnings (errors) with my default compilation options.)
Osiris JL: make bs97 && bs97
gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes bs97.c -o bs97
12345
Osiris JL:
This time, the 4 and the 5 are still visible.
Simply using backspace does not erase the content that was previously there; it positions the write position on screen back one place, that's all. If you want to erase what was there, you need to output printf("\b \b\b \b") to go back, output a space, and go back again — repeated twice. Or you could use printf("\b\b "), but that would leave the write position after the two spaces; or you could use printf("\b\b \b\b") to leave the write position after the 3. And there are other variations on this theme.
With the second program with the sleep, I get similar behaviour, except that the 12345 is on display while the program sleeps.
I'm testing on a Mac running macOS 10.14 Mojave, using a home-built GCC 8.2.0 or the clang compiler from XCode 10.0.
I am using Vim as my editor and GCC as my compiler, but it’s not working quite right. Let‘s say I am making a basic program to determine if a number is odd or even. Here is my code:
#include <stdio.h>
int main(int argc, char argv[])
{
int i;
printf("Enter a number: ");
scanf("%d\n", &i);
printf("%d\n", i);
if(i % 2 == 0)
{
printf("Your number is even.\n");
}
else if(i % 2 != 0)
{
printf("Your number is odd.\n");
}
else
{
printf("Invalid input.\n");
}
getchar();
return 0;
}
I'm not sure if I am programming this wrong, or gcc is just not a good compiler, or whatever. I am running linux, which I dual boot with windows. Now I press ctrl-d to stop the process, and only then does it print me back my number, and tell if it is odd or even. It isn't just this one, a lot of other programs with similar formats seem to do this to.
~ $ ./test
Enter a number: 45
45 //I press enter, nothing happends. Ctrl-d
Your number is even. //ctrl-d again
~ $
So what I'm asking is, is there a way to program it so that I don't have to quit the program in order for it to work, or is there another compiler that wouldn't have this problem? I am running on Ubuntu 14.04 dual booted with Windows 8.1.
\n in the format for scanf means "read until hit into non-whitespace character and then ignore them". Remove it and make the format for reading "%d".
to get gcc to work from vim,
goto the vim command prompt
shell gcc <and all needed parameters>
Or open another command window
set it to the same directory as the program being edited
gcc <and all needed parameters>
in general, try to make the compile step separate from the link step. I.E. to compile:
gcc -c <mySource.c> -Wall -Wextra -pedantic -std=c99 -o mySource.o
if any header files, other than those in the default 'include' path then add
-I<pathToHeaderFile>
which is often in the same directory so would be:
-I.
then link with:
gcc mySource.o -o mySource
You can add the -ggdb parameter to both lines if you plan on doing any debugging.
to add any library directories then on the link step append
-L<pathToLibrary>
to add any libraries then on the link step append, after any library parameters:
-l<shortLibName>
The initialization file for vim can contain the necessary info to invoke gcc by some keystroke combination, but I'm not totally familiar with the details.
I'm compiling the below C code with gcc. No errors are thrown during compilation or at runtime. I ran through the code with gdb, and the answer given in sum is correct at the end, yet the printf() does not display anything on the screen. I've tried all sorts of combinations of fprintf(), printf(), and fflush(), but nothing works.
What do I need to change so the program will print the result to stdout?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num = 9;
int i, sum; i = 1, sum = 0;
while (i < 2 * num) {
sum = sum + i * i;
++i;
}
printf("sum: %d\n", sum);
fflush(stdout);
return 0;
}
The code is correct, and should print sum: 1785 for any conforming implementation.
This is a guess (update: which turns out to be correct), but ...
You've named the source file test.c, and you compile it with:
$ gcc test.c -o test
(or something similar) and execute it with:
$ test
which produces no output.
The problem is that test is a standard Unix command (and also a built-in command in some shells). When you type a command name to the shell, it first looks for built-in commands, then for executables in directories specified in your $PATH environment variable.
To execute a command in the current directory, prepend ./ to the name:
$ ./test
sum: 1785
$
This applies to any command in the current directory. There are so many built-in commands that you can't reasonably avoid colliding with them. Cultivating the habit of running executables in the current directory by typing ./whatever means that name collisions don't matter.
(Don't be tempted to add . to the front of your $PATH; that's dangerous. Think about what could happen if you cd into a directory and type ls, if there happens to be a malicious ls command there.)
There is nothing wrong with your program. It has to work. Try running it with redirection:
./a.out > myout
..and see if you get any output. If not, I'd suspect there is a problem with some kind of standard library mismatch.
Another option to check would be to build using SUN C compiler as opposed to gcc and see if that works. If it does, gcc is the culprit.
For reference, I'm copying this example (nearly) letter for letter from page 18 in The C Programming Language, Second Edition.
#include <stdio.h>
/*count characters in input, 2nd version*/
main(){
double n;
for (n = 0; getchar() != EOF; ++n)
;
printf("%.0f\n", n); /*this never prints*/
}
I wasn't sure if it was my version of gcc (I'm a noob):
% gcc --version
gcc (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
Copyright (C) 2010 Free Software Foundation, Inc.
Because
for (n = 0; getchar() != EOF; ++n)
printf("%.0f",n); /*returns 0123456...n*/
I tried printing "foo" instead of value n, just to see. It still isn't printing.
What am I missing here? I don't like moving ahead while ignoring little problems like these.
=====================================
EDIT
So the end result should be:
% gcc ./counter.c -o ./counter
% ./counter
foo
3
Right now, this is the output from the first snippet:
% ./counter
foo
0123
And the second one:
% ./counter
foo
^C
%
If you are on an OSX or linux box, you need to type Ctrl+D on its own line to generate an EOF character. On Windows, Ctrl+Z on its own line. Don't type Ctrl+Z on a unix box because that will just send your proces to the background.
You are typing Ctrl+C which is break, and will send a SIGTERM to your program.
On my mac, I get:
$ ./foo
hello
6D
Or if you don't want to signal the EOF condition, use echo and a pipe:
$ echo "hello" | ./foo
6
Note that the EOF has to be on its own line. a ^D is printed, and then 6 overwrites the ^, so it looks like the output is 6D.
Of course, in the two above examples, the characters being counted are h e l l o \n. If you don't want a newline, do this:
$ echo -n "hello" | ./foo
5
You shouldn't have that semi-colon after the for. That means the only thing in your loop is an empty statement.
Actually, David is correct. The empty statement is the only thing in the loop, but that's fine. It will count the number of characters. Then, outside the loop, it will print the total.
This demo shows that it works as intended (6-character input results in printing 6). However, I would use braces, or keep the indentation as in the original for clarity.