Printing all characters in a string in C - c

I have a very simple program to print the chars in a string but for some reason it is not working:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void * print_chars(char *process_string) {
int i;
int string_len;
string_len = strlen(process_string);
printf("String is %s, and its length is %d", process_string, string_len);
for(i = 0; i < string_len; i++) {
printf(process_string[i]);
}
printf("\n");
}
int main(void) {
char *process_string;
process_string = "This is the parent process.";
print_chars(process_string);
return 0;
}
When I run it in Netbeans, I get the following:
RUN FAILED (exit value 1, total time: 98ms)
If I remove the line
printf(process_string[i]);
the program runs but nothing prints out to the console (obviously).
Any ideas what I'm missing here?

You need a format in the line
printf(process_string[i]);
i.e.
printf("%c", process_string[i]);

There are a couple of problems.
One is that you're not seeing any output from the printf("String is %s, and its length is %d", ...). This is because standard output is line buffered by default, and you are not including a newline, so it never actually decides that there's a line ready to print. If you change the format string to add a \n, you will see the output from this command.
The second is that you are passing a char into the first argument of printf(), where it expects a char *. This causes it to crash, as it tries to interpret that character as a pointer. You want to pass something like printf(process_string) instead. However, it's generally a bad idea to pass a variable string directly into the first argument of printf(); instead, you should pass a format string that includes %s, and pass the string in as the corresponding argument: printf("%s\n", process_string). Or, if you want to print it character by character, printf("%c", process_string[i]), followed by a printf("\n") to flush the buffer and actually see the output. Or if you're doing it character by character, putchar(process_string[i]) will be simpler than printf().

printf() expects, as first parameter, a pointer to char. What you are passing is a char, not a pointer to one.
Anyway, printf() is not the function to use here. Try putc()...

Related

C : printf function not printing when I input element of an array

I am trying to print an element of the cube_pattern string, but when I execute my code nothing is printed to the console and my code freezes for a few seconds:
#include <stdio.h>
#define SOLVED_CUBE "UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB"
char cube_pattern[54] = SOLVED_CUBE
void print_pattern() {
printf("%s", cube_state[0]);
}
void main() {
print_pattern();
}
I tried calling fflush(stdout) but it still doesn't work:
void print_pattern() {
printf("%s", cube_state[0]);
fflush(stdout);
}
"UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB" contains 54 characters. Your char array only can store 54 characters. This does not leave space for a null terminator. Thus when you try to print using the %s specifier, you invoke undefined behavior. Maybe when it looks for the 55th character, it finds 0, but maybe not.
I don't see that using #define gains you anything. I would simply:
char cube_pattern[] = "UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB";
Your code has multiple errors. First, you have multiple typos. For example, cube_state should be cube_pattern. Second, you are using the printf() formatter %s, but only passing it one character (cube_pattern[0]). Lastly, your array is only 54 bytes long, but your string needs 55 bytes (54 characters + one NULL character).
This code works for me:
#include <stdio.h>
char cube_pattern[55] = "UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB";
void print_pattern() {
printf("%s\n", cube_pattern);
}
int main() {
print_pattern();
}
I have also changed printf("%s", cube_pattern); to printf("%s\n", cube_pattern);. Adding a new line will flush the buffer if your output is line-buffered, which is generally what you want. Alternatively, you could also use fflush(stdout).

Why does the output of my program contain an extra newline?

I'm trying to do a naive implementation of the C-standard function printf. So far I've just written some testing code to help me better understand the use of variable arguments lists. However, I don't know why my output contains an extra line.
Here is my code:
#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>
void print_test_helper(char *string, va_list args)
{
while (*string)
{
if (*string == '%')
{
string = string + 2; //increment pointer by two spots to "\n"
printf("%s", (va_arg(args, char*)));
}
else
{
write(1, &*string, 1);
string++;
}
}
}
void print_test(char *string, ...)
{
va_list ap;
va_start(ap, string);
print_test_helper(string, ap);
}
int main()
{
print_test("this is a %s\n", "string");
return 0;
}
The way I see it, my print_test_helper should keep writing the string passed to it up until it sees the '%' character, after which it skips two spots to the newline character. The function then calls the printf method to simply printout the argument held in the list, but the output is like so:
this is a
string
As you can see, it contains a new line. Any ideas why?
Edit:
changing the line printf("%s", va_arg(args, char*)) to write(1, va_arg(args, char*), 6); produces the expected behavior. Is this an issue with the interaction between write and printf?
Edit 2:
See the answer below!
#Achal pointed me in the right direction about buffering in the printf. As far as I can tell according to this stack overflow post, printf isn't guaranteed to print to the console unless a few conditions are met. A few of those namely being an fflush, a program exit, or a newline.
In my case, the function was writing out every character to the stdout (write is not buffered) and when it encountered the "%s\n", printf was doing its job, only it was buffered. So my assumption is that when "\n" gets written to the stdout, printf realizes it needs to dump its buffer and it does so, only after write puts down the newline.
As mentioned by #M.M it's not a good idea to mix write and printf and I guess this post is testament to that. I didn't intend to end up with it like that though, I was simply using printf for testing since I was lazy, but I ended up learning more about how it works. Cheers.

problems with c pointer strings

:)
I'm trying to beat string pointers in c, so I write this code but I didn't get the result that I expected.
I'm creating a string variable, and I want to pass it to a function that check if the string lenght is bigger than 10.
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
bool is_bigger_than_10(char *);
int main()
{
char *string1 = "";
int i = 0;
printf("Initial string: %s\n",&string1);
printf("Size is: %d\n",strlen(&string1));
printf("Give me one string: ");
scanf("%[^\t\n]s",&string1); //This scan allows me to enter string with spaces
printf("You write: %s\n", &string1);
printf("Size is: %d\n",strlen(&string1));
printf("String character by character:\n");
for(i = 0; i < strlen(&string1) ; i++)
{
printf("%c ",&string1[i]);
}
printf("\nNow let's check if it's bigger than 10\n");
printf("Answer is: %d",is_bigger_than_10(&string1));
return 0;
}
bool is_bigger_than_10(char *textx)
{
printf("%s --> %d > %d\n",&textx, strlen(&textx),10);
if(strlen(&textx) > 10)
{
return true;
}
else
{
return false;
}
}
The expected output should be:
Initial string:
Size is 0:
Give me one string: axel
You write: axel
String character by character:
a x e l
Now let's check if it's bigger than 10
a x e l --> 4 > 10
Answer is: 0
If yoy run that code and enter axel as the input string you will get this:
Initial string: $0#
Size is 3:
Give me one string: axel
You write: axel
String character by character: a b c d e
a x e l
Now let's check if it's bigger than 10
' --> 3 > 10
Answer is: 0
It's kind of weird, could some one help me to correct this code?
There are two things going on here:
First, your char pointer needs to point somewhere. With the line
char *string1 = "";
you create a pointer to a string literal, which you can't write to. (Obviously you can, given your output, but you just got lucky on a system that allows it.) Create a character buffer instead:
char string1[200] = "";
and ideally enforce the constant buffer limit when you read the string.
Second, you don't need all these &s. The & is not a magic marker that you have to prepend to all your arguments.
The & takes the address of a variable and passes it as a pointer. You need that when the called function needs to change the variable via the pointer. Printing doesn't need to change anything, so unless you want to print the address of a variable with %p, you shouldn't pass addresses. (In the special case of your program, you can just remove all ampersands with search and replace.)
When scanning, you need to change variables if you convert input to numbers or if you scan a char. The exception is when you scan strings with %sor %[...]: Here, you pass a char buffer (as a pointer to its first elements) and the function then fills that buffer.
The problem with scanf and printf is that the arguments after the format string are variadic, which means they will accept any arguments without type checking. The good thing is that most compilers can tell whether a format string matches the arguments and will issue warnings, it you enable them. Do yourself a favour and do that.
(Warnings will also tell you that you have type mismatches in functions where the type of the argument is known, such as your is_bigger_than_10.)

Code blocks output console has stopped working

Whenever i declare a varible as char and scan it as string "%s" my output console crashes. Here is the code
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int main()
{
char a[20];
int i;
printf("Enter a name ");
scanf("%s",&a);
for(i=0;i<strlen(a);i++)
{
a[i] = toupper(a[i]);
i++;
printf("%s\n",toupper(a[i]));
}
return 0;
}
The second i++; inside the for loop body may cause the index to point off-by-one then, printf("%s\n",toupper(a[i])); will be out of bound access which invokes undefined behavior.
You can remove the i++ from inside the loop body.
Next, toupper(a[i]) returns an int, which is invalid for %s format specifier, which again invokes UB.
That said,
to prevent buffer overflow from excessive long input, it's best to limit the input length with scanf(),
You don't need to pass the address of an array, just the array name will be sufficient
So, overall, you should write
scanf("%19s",a);
You have two problems in the loop where you use toupper and print.
The first is that you increment the variable i twice in the loop.
The second problem is the printf:
printf("%s\n",toupper(a[i]));
Here you ask printf to print a string, but as argument you give it a single character (actually an int, toupper returns an int). Use the "%c" format specifier to print a single character.
By the way, you don't need to call toupper when printing, as the character should already be in upper-case because of the previous assignment.
Your printing loop is mis-behaving and giving you undefined behavior:
printf("%s\n",toupper(a[i]));
is passing toupper(a[i]) to printf()'s %s format specifier, which requires a char * not a plain char. That triggers undefined behavior.
There's no point in printing each character one by one, instead convert the entire string to upper case, then print it once:
for(i = 0; a[i] != '\0'; ++i)
{
a[i] = (char) toupper((unsigned char) a[i]);
}
printf("%s\n", a);
The casts around toupper() are sometimes needed since it takes and returns int, and you want to be a bit careful about when converting to/from characters.
Notice that I factored out the call to strlen(), this might be a bit "too clever" but it's how I would expect this code to be written. If we're going to loop over the characters, there's no need to compute the length separately.

printing string in c using a pointer

I was just printing some characters in C.
I have declared char c and assigned its characters.
then using a for loop i try to print the characters one by one.
I have used pointers, of course.
#include <stdio.h>
#include <string.h>
int main()
{
char c[4] = {"hia"};
int i;
for(i=0;i<4;i++)
{
printf(&c[i]);
}
return 0;
}
However when I compile my code using turbo, i get output "hiaiaa" instead of "hia"! What am i doing wrong here?
Your printf() call is broken. You are using the string (from the point you specify) as the formatting string. This will not print single characters. Instead each call will print from where its formatting string starts, to end of the string.
This means the first call will print all of c, the next will print from c[1] and onwards, and so on. Not at all what you wanted.
If you want to print single characters, use the %c format specifier:
printf("%c", c[i]);
No pointer necessary, since the character is passed by value to printf().
This is what happened in your loop:
0. hia
1. ia
2. a
3. \0
However, you want to print exactly one char at a time, not a null terminated string, so you should pass it as char not a char*:
printf( "%c", c[i] )
Also, you are looping four times, but string length is just three. You should use:
for( i = 0; i < strlen( c ); i++ )
...
The printf function have an char* as first argument, that's correct. However, it prints a string (that is, a zero-terminated sequence of char) so it will always do that.
If you want to print one character at a time, then you have to use that format, like in:
printf("%c\n", c[i]);
You also have another problem, and that is that you try to print the zero terminator as well. This character is not printable so will not show. Use e.g. i < strlen(c) as the loop condition to overcome this.
Also, instead of printing character-by-character, print it all as one string:
printf("%s\n", c);
1) For loop size should i<3 , not i<4 (i=3 refers to the null character at the end of the string)
2) use printf("%c",c[i]);
Explanation of what you're seeing: In each loop, printf is printing a null-terminated string. This string starts in every loop one char later inside your array.
How it should be done, depends on what you're intending. If you want to print the string char by char via pointer you may use:
char *p=&c[0];
while (*p) {
printf("%c", *p);
p++;
}
Your question is to print string using pointer. You could use
printf("%s", c);
or character by character as (include library string.h for this)
for(i=0;i<strlen(c);i++)
{
printf("%c", c[i]);
}
in C strings are stored as character arrays and are terminated by a zero-value, so called zero-terminated strings. Btw, this is why you have to make the array size of 4 for thee real chars.
In your example, you are passing pointers th each char to the printf function and printf prints the strings from your pointer to the next null-value . The 1st pass prints "hia", the 2nd ia and the 3rd a.
To print a single char in each pass, you have to use
printf ("%c", c[i]);
Your loop will call printf with the following parameter:
printf("hia"); // first loop iteration
printf("ia"); // second loop iteration
printf("a"); // third loop iteration
printf(""); // fourth loop iteration
You probably meant to print one character at a time:
for(i=0;i<3;i++) // No need to print the string termination character.
{
printf("%c", c[i]); // "%c" is the printf format code to print a single character
}

Resources