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

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).

Related

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.

Compare a variable and a string

I am trying to code a C program to start specific functions on the OS X El Capitan.
The code looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char mainchoice;
printf(">>> ");
scanf("%s", &mainchoice);
if (strcmp(&mainchoice, "start ftp") == 0) {
system("ftp");
}
else if (strcmp(&mainchoice, "start say") == 0) {
system("say hello");
}
else {
system("say Error")
}
}
This is just a sample code.
When I run it, it always says error via the say command. What am I doing wrong?
Focus here:-
char mainchoice; //declared as a char
scanf("%s", &mainchoice); //using the %s placeholder which is for string
//for character it is %c
Getting the logic behind your code is you want to enter a String not a character.
Make an array of characters like this:-
char mainchoice[20]; //this can hold your string, one character at one index each of the array
Since, your are using multi word in string comparison("start say")
(strcmp(&mainchoice, "start say") == 0)
scanf does not work for multi words. scanf stops reading from the keyboard as soon as you provide a whitespace, tabs, newline.
For solving that problem, use fgets. It's the best way to read multi words or even whole sentences. Never use gets()! It is vulnerable to buffer overflow!
fgets(mainchoice, 20, stdin);
you are declaring mainchoice as a character rather then a string.
use char mainchoice[10]; to create a string.
and replace scanf("%s",&mainchoice) with fgets(mainchoice, 10, stdin);
size is 10 because you are comparing it with a string of length 9, so(9+1 null=10) 10 are enough.

Given a string write a program to generate all possible strings by replacing ? with 0 and 1?

I have written this code it is working fine for a?b?c? and a?b?c?d? but for a?b?c?d?e? it is giving one additional garbage value at the end. At the end of s there is '\0' character attached then why and how is it reading that garbage value. I tried to debug it by placing printf statements in between the code but couldn't resolve it. please help.
#include<stdio.h>
void print(char* s,char c[],int l)
{
int i,j=0;
for(i=0;s[i]!='\0';i++)
{
if(s[i]=='?')
{
printf("%c",c[j]);
j++;
}
else
printf("%c",s[i]);
}
printf(", ");
}
void permute(char *s,char c[],int l,int index)
{
if(index==l)
{
print(s,c,l);
return;
}
c[index]='0';
permute(s,c,l,index+1);
c[index]='1';
permute(s,c,l,index+1);
}
int main()
{
char s[10],c[10];
printf("Enter a string.");
scanf("%s",s);
int i,ct=0;
for(i=0;s[i]!='\0';i++)
{
if(s[i]=='?')
ct++;
}
permute(s,c,ct,0);
return 0;
}
My output was like this :-
a0b0c0d0e0♣, a0b0c0d0e1♣,
...and so on.
As we can see from your code, with an array defined like char s[10] and the input being
a?b?c?d?e?
is too big an input to be held in s along with the null-terminator by
scanf("%s",s);
You need to use a bigger array. Otherwise, in attempt to add the terminating null after the input, the access is being made to out-of-bound memory which invokes undefined behaviour.
That said, never allow unbound input to the limited-sized array, always use the field-width to limit the input length (in other words, reserve the space for null-terminator), like
scanf("%9s",s);
The code is producing the correct output here, but note that it has undefined behavior for strings of size greater than or equal to 10 chars, because that's the size of your buffer.
So, for a?b?c?d?e? you need a buffer of at least 11 characters, to account for the null terminator. You should make s bigger.
See actually in C what happens in String is that everytime it appends a '\0' character at last.
Now notice in C there is nothing called string.
It's array of characters.
So if you have defined like this-
char s[10]
This actually accepts an array of less than of 9 characters as the last one will be the '\0' character.
If you add more than 9 character it will give erroneous output.

What is wrong with the program?

I'm extremely new to C and am doing a few problems I found in a book I bought. What is wrong with this program?
int main (void)
{
char text[50]='\0';
scanf ("%s", text);
printf("%c", text[49]);
printf("%s", text);
return 0;
}
char text[50]='\0';
is not valid. You could skip initialising text and just declare it
char text[50];
or you could initialise its first element
char text[50]={'\0'};
You're also missing an include of stdio.h and should really check that your scanf call read a string and could give it a max length for the string
if (scanf("%49s", text) == 1)
You want to get rid of:
printf("%c", text[49]);
as you have no idea what's at that memory location if the string is less than 49 chars long.
There is a difference of single quotes and double quotes in C.
double quotes means string
single quotes means character
Line 3 will not compile because the compiler wants you to assign a string to the array of characters.
You can do
char text[50]="\0";
which in effect fills all the 50 bytes with zeros.
You could also do
char text[50]="bla";
which fills the first 3 bytes with "bla" and the rest with zeros. At least my compiler does it like that.
You could also do nothing because you anyway fill it with user input just the next statement.
char text[50];
scanf ("%s", text);
But then you have a problem. Because the very next statement will give you random output if the user has entered a string with less than 49 characters. But if you initialize, well then you output the zero byte, which is also quite useless.
The main point however is to learn the different behaviour of C when dealing with an array of characters.
int main ()
{
char text[50]={'1','2','3','4'};
printf("%c", text[1]);
printf("%c",text[0]);
getch();
return 0;
}
do like this..

Printing all characters in a string in 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()...

Resources