I'm beginer in C/C++ programming.
This is my program that displays binary numbers in ascending order in the terminal (I'm compiling in Linux Mint).
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
void reverse(char *x, int begin, int end)
{
char c;
if (begin >= end)
return;
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
reverse(x, ++begin, --end);
}
int main()
{
unsigned int bitCount;
unsigned int naborCount;
printf("Число битов в наборе: ");
scanf("%d", &bitCount);
printf("\n");
naborCount = pow(2, bitCount);
char naborStr[bitCount*2];
for(int i = 0; i<naborCount; i++)
{
for(int j = 0; j<bitCount; j++)
{
if((i & (1<<j))==0)
{
strcat(naborStr, "0 ");
}
else
{
strcat(naborStr, "1 ");
}
if(j == bitCount-1)
{
reverse(naborStr, 0, strlen(naborStr)-1);
printf("%s \r\n", naborStr);
memset(naborStr, 0, sizeof(naborStr));
}
}
}
return 0;
}
This is what I see in the terminal
Where did this symbol come from? How to solve it?
C strings are null terminated.
The %s specifier searches for a null termination.
In your case it keeps on printing until it finds one, so you get some random symbols.
Try making use of null character at the end of the string and check.
Have a look at the following implementation:
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
void reverse(char *x, int begin, int end)
{
char c;
if (begin >= end)
return;
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
reverse(x, ++begin, --end);
}
int main()
{
unsigned int bitCount;
unsigned int naborCount;
printf("Число битов в наборе: ");
scanf("%d", &bitCount);
printf("\n");
naborCount = pow(2, bitCount);
char naborStr[bitCount*2 + 1]; //Increased size by 1 for null character
for(int i = 0; i<naborCount; i++)
{
for(int j = 0; j<bitCount; j++)
{
if((i & (1<<j))==0)
{
strcat(naborStr, "0 ");
}
else
{
strcat(naborStr, "1 ");
}
if(j == bitCount-1)
{
reverse(naborStr, 0, strlen(naborStr)-1);
naborStr[bitCount*2 +1] = '\0'; //Appending null character
printf("%s \r\n", naborStr);
memset(naborStr, 0, sizeof(naborStr));
}
}
}
return 0;
}
Related
As stated in the title I am trying to find all lower-case letters that are not in a series of words. There are no upper-case letters, digits, punctuation, or special symbols.
I need help fixing my code. I am stuck and do not know where to go from here.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
int letters[26];
char words[50];
int i = 0, b = 0;
printf("Enter your input : ");
scanf("%s", words);
for(i = 0; i < 26; i++){
letters[i] = 0;
}
while(!feof(stdin)){
for(b = 0; b < strlen(words) - 1; b++){
letters[ words[b] - 'a']++;
scanf("%s", words);
}
}
printf("\nMissing letters : %c ", b + 97);
return 0;
}
My output is giving me some random letter that I do not know where it is coming from.
Here is a working first implementation.
As well as the comments that have already been made, you should use functions wherever possible to separate out the functionality of the program into logical steps. Your main function should then just call the appropriate functions in order to solve the problem. Each function should be something that is self contained and testable.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_INPUT 20 /* Max input to read from user. */
char *readinput(void);
void find_missing_lower_case(char *, int);
int main()
{
char *user_input = readinput();
int len_input = strlen(user_input);
printf("user input: %s\n", user_input);
printf("len input: %d\n", len_input);
find_missing_lower_case(user_input, len_input);
/* Free the memory allocated for 'user_input'. */
free(user_input);
return 0;
}
char *readinput()
{
char a;
char *result = (char *) malloc(MAX_INPUT);
int i;
for(i = 0; i < MAX_INPUT; ++i)
{
scanf("%c", &a);
if( a == '\n')
{
break;
}
*(result + i) = a;
}
*(result + i) = '\0';
return result;
}
void find_missing_lower_case(char *input, int len_input)
{
int a = 97; /* ASCII value of 'a' */
int z = 122; /* ASCII value of 'z' */
int lower_case_chars[26] = {0}; /* Initialise all to value of 0 */
/* Scan through input and if a lower case char is found, set the
* corresponding index of lower_case_chars to 1
*/
for(int i = 0; i < len_input; i++)
{
char c = *(input + i);
if(c >= a && c <= z)
{
lower_case_chars[c - a] = 1;
}
}
/* Iterate through lower_case_chars and print any values that were not set
* to 1 in the above for loop.
*/
printf("Missing lower case characters:\n");
for(int i = 0; i < 26; i++)
{
if(!lower_case_chars[i])
{
printf("%c ", i + a);
}
}
printf("\n");
}
I figured it out and this is the code I used.
int main(void)
{
int array[26];
char w;
int i=0;
for(i=0; i<26; i++) {
array[i]=0; }
printf("Enter your input: ");
scanf("%c", &w);
while(!feof(stdin)) {
array[w-97] = 1;
scanf("%c", &w); }
printf("Missing letters: ");
for(i=0; i<26; i++) {
if(array[i] == 0) {
printf("%c ", i+97); }
}
printf("\n");
return 0;
}
Do anybody knows how to search for a name in a string array? If i register the name 'jacob' and search for cob I need to get jacob shown instead of not showing up anything. I don't know if strcmp is the right way to do it. Any ideas?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
struct name{
char name[MAX];
};
void getRegister(struct name name[], int *nrNames);
void getSearch(struct name name[], int nrNames);
int readLine(char s[], int length);
int main(){
int run=1;
struct name name[MAX];
int nrNames=0;
while(run){
char choice;
printf("\n (1)Register\n(2)Search\n(3)Quit\n");
scanf(" %c%*c", &choice);
if(choice=='1') getRegister(name, &nrNames);
if(choice=='2') getSearch(name, nrNames);
if(choice=='3') run=0;
}
return 0;
}
void getRegister(struct name name[], int *nrNames){
char input[MAX];
printf("Enter name: ");
readLine(input, MAX);
(*nrNames)++;
}
void getSearch(struct name name[], int nrNames){
int i;
char input[MAX];
printf("Enter name: ");
readLine(input, MAX);
if(i>=0){
printf("Name/s:\n");
for(i=0; i<nrNames;i++){
if(strcmp(input, name[i].name)==0){
printf("\n%s\n",name[i].name);
}
}
}
}
int readLine(char s[], int length){
int ch, i=0;
while(isspace(ch=getchar()));
while(ch!='\n' && ch!=EOF) {
if(i<length) s[i++]=ch;
ch = getchar();
}
s[i]='\0';
return i;
}
Try to search for the match in the array. The code below displays a position for each occurrence of the second array in the first array. It uses naive approach. There are more efficient algorithms like Knuth-Morris-Pratt or Boyer-Moore algorithm.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
int main(){
char c;
char name[MAX], search_name[MAX];
int i = 0, j = 0, match = 0, count = 0;
printf("Register name: ");
while ((c = fgetc(stdin)) != '\n') {
if (i < MAX){
name[i++] = c;
}
}
name[i] = '\0';
printf("Search name: ");
i = 0;
while ((c = fgetc(stdin)) != '\n') {
if (i < MAX){
search_name[i++] = c;
}
}
search_name[i] = '\0';
i=-1;
match = 0;
do {
i++;
j = 0;
do {
if (name[i+j] == search_name[j])
match = 1;
else {
match = 0;
break;
}
j++;
} while (search_name[j] != '\0');
if (match)
printf("Match on position %d ", i);
} while (name[i+j] != '\0');
printf("\n");
return 0;
}
I found the soulution myself. Here is the code for those who get stuck as I did.
void searchName(const struct varor reg[], int nrOfGoods){
int i;
char name[20];
printf("Enter name: ");
readLine(name, WORDLENGTH);//gets input
if(i>=0){
printf("\nId.number \t Name \t\t\t Quantity\n");
for(i=0; i<nrOfGoods;i++){
if(strstr(reg[i].name, name)!=NULL){ //this should do the job
printf("%-17d%-24s%-5d\n",reg[i].idnumber,reg[i].name.reg[i].quantity);
}
}
}
}
I'm learning basics in coding. Can any one say what went wrong with my code
Prob:Given a string, S, of length N that is indexed from 0 to N-1 , print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
char input[100], final[100];
int main()
{
int num, i, j;
char even[50], odd[50], space[] = " ";
scanf("%d", &num);
for (i = 0; i < num; i++)
{
int k = 0, p = 0;
scanf(" %[^\n]s", input);
for (j = 0; input[j] != '\0'; j++)
{
if (j % 2 == 0)
{
even[k] = input[j];
k++;
}
else
{
odd[p] = input[j];
p++;
}
}
strcat(final, even);
strcat(final, space);
strcat(final, odd);
}
printf("%s", final);
}
My program is fairly simple.
Read the H,W, horizontal char, vertical char from a user.
And then print out the square by the given params.
However, when user type 'y' to run the second time.
the height param is always missing.
I didn't get it.
A likely buggy point i can think is that the input buffer might not clean.
Any idea?
C program
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <memory.h>
const int USER_INPUT_SIZE_EACH_LINE = 999;
void draw_middle_lines(char *middle_line, int width) {
printf("%s", middle_line);
for (int i = 2; i < width; i++) {
printf(" ");
}
printf("%s\n", middle_line);
}
void draw_bound_line(char *bound_char, int width) {
for (int i = 0; i < width; i++) {
printf("%s", bound_char);
}
printf("\n");
}
void clearNewline(char *line, int max_len) {
for (int i = 0; i < max_len; i++){
printf("%c", line[i]);
}
printf("\n");
for (int i = 0; i < max_len; i++) {
if (line[i] == '\n') {
line[i] = '\0';
}
}
}
char **ask_user_preference() {
printf("\nask user preference\n");
const int NUM_OF_PROMPTS = 4;
const char *prompt[] = {
"please input height:",
"please input width:",
"please input horizontal char:",
"please input vertical char:",
};
char **preference;
preference = malloc(NUM_OF_PROMPTS);
for (int i = 0; i < NUM_OF_PROMPTS; i++) {
preference[i] = malloc(USER_INPUT_SIZE_EACH_LINE);
memset(preference[i], 0, sizeof(char) * USER_INPUT_SIZE_EACH_LINE);
printf("%s", prompt[i]);
fgets(preference[i], USER_INPUT_SIZE_EACH_LINE, stdin);
clearNewline(preference[i], USER_INPUT_SIZE_EACH_LINE);
}
return preference;
}
void draw(int w, int h, char *bound_char, char *middle_char) {
printf("width: %d\n", w);
printf("height: %d\n", h);
draw_bound_line(bound_char, w);
for (int i = 2; i < h; i++) {
draw_middle_lines(middle_char, w);
}
draw_bound_line(bound_char, w);
}
void clr_input_buffer() {
for (;;) {
int c = getchar();
if (c == EOF || c == '\n')
break;
}
}
int main() {
char *cont = malloc(10+1);
do {
char **pref = ask_user_preference();
int height = atoi(pref[0]);
int width = atoi(pref[1]);
char *bound_char = pref[2];
char *middle_char = pref[3];
draw(width, height, bound_char, middle_char);
printf("continue to play (y/n)? ");
fgets(cont, 2, stdin);
if (strncmp(cont, "y", 1) == 0) {
clr_input_buffer();
}else{
break;
}
} while (1);
printf("BYE BYE~");
return 0;
}
I am writing a program where I need to convert Ascii characters to binary and then do a count. I have gotten my code working but it is printing additional information and not necessarily the correct binary. Below is my code as well as the output for a given set of characters. Any assistance would be greatly appreciated!
#include <stdio.h>
#include <stdlib.h>
void binaryPrinter(int digEnd, int value, int * noOfOnes);
void print(char c);
int charToInt(char c)
{
return (int) c;
}
int main()
{
char value;
int result = 1;
while(result != EOF)
{
result = scanf("%c", &value);
if(result != EOF)
{
print(value);
}
}
}
void binaryPrinter(int digEnd, int value, int * noOfOnes)
{
if(value & 1)
{
(*noOfOnes) = (*noOfOnes) + 1;
value = value >> 1;
digEnd--;
printf("1");
}
else
{
value = value >> 1;
digEnd--;
printf("0");
}
if(digEnd == 0)
return;
else
binaryPrinter(digEnd, value, noOfOnes);
}
void print(char c)
{
int count = 0;
printf("The character %c =", c);
binaryPrinter(8, charToInt(c), &count);
printf(" 1's = %d\n", count);
}
Here's a pair of functions:
void printCharAsBinary(char c) {
int i;
for(i = 0; i < 8; i++){
printf("%d", (c >> i) & 0x1);
}
}
void printStringAsBinary(char* s){
for(; *s; s++){
printCharAsBinary(*s);
printf(" ");
}
printf("\n");
}
You can see them in action here: http://ideone.com/3mEVbE. They work by masking out a single bit of each character and printing one at a time.