Keep characters in an array - c

I want to do a program that ask to the user to give one character, then enter... until he wants to stop by pressing enter and no caracters.
Then, the program will say: "you gave the caracters ...."
for example:
give the caracter 1: k + enter
give the caracter 2: l + enter
give the caracter 3: just enter ('\n')
result: You gave the caracters: kl
My code doesnet work because when i just press enter, nothing happen. Here is the code:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
while (str[i] != '\n') {
printf("element number str[%d] : ", i);
scanf("%s", &str[i]);
i++;
}
printf("The string is: ");
while (j < i) {
printf("%s", str[j]);
j += 1;
}
return 0;
}

You can do it with c = getchar(); or c = fgetc(stdin) function:
#include <stdio.h>
#define N 1000
int
main ()
{
int i = 0;
int j = 0;
int c;
char str[N];
while (1)
{
c = fgetc(stdin); // or c = getchar();
if ( (c != EOF) && (c != 0x0A ) ) // 0x0A = 'nl' character
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}
printf ("The string is: %s", str);
return 0;
}
OUTPUT:
This is my string!
element number str[1]=T
element number str[2]=h
element number str[3]=i
element number str[4]=s
element number str[5]=
element number str[6]=i
element number str[7]=s
element number str[8]=
element number str[9]=m
element number str[10]=y
element number str[11]=
element number str[12]=s
element number str[13]=t
element number str[14]=r
element number str[15]=i
element number str[16]=n
element number str[17]=g
element number str[18]=!
The string is: This is my string!
Or you can use your original scanf("%s", &str1);
#include <stdio.h>
#define N 1000
int main ()
{
int i = 0;
int k = 0;
int c;
int len;
char str[N];
char str1[N];
scanf("%s", &str1);
len = strlen(str1);
for(k = 0; k < len; k++)
{
c = str1[k];
if ( (c != EOF) && c != '\n') // EOF will work for ^D on UNIX
{
str[i] = (char) c;
printf ("element number str[%d]=%c \n", i, str[i++] );
}
else
{
str[i] = 0;
break;
}
}
printf ("The string is: %s", str);
return 0;
}
OUTPUT:
12345
element number str[1]=1
element number str[2]=2
element number str[3]=3
element number str[4]=4
element number str[5]=5
The string is: 12345

As stated in this answer scanf will not return until you give it a string, i.e. it skips whitespace.
As suggested in the answer and in general, using fgets is the better option.
Edit: A way to accomplish what you want would look like this:
#include <stdio.h>
#define N 1000
int main() {
int i = 0;
int j = 0;
char str[N];
do {
printf("element number str[%d] : ", i);
fgets(&str[i], 3, stdin);
i++;
} while (str[i - 1] != '\n');
printf("The string is: ");
while (i > j) {
printf("%c", str[j]);
j++;
}
return 0;
}
In the fgets you use the number 3 because pressing enter gives both a newline character [/n] and a return carriage [/r].

Related

How can I pass a stdin as an argument for my function?

My first program. I would like it if the user enters a word made of letters and then it uses my loop function to output mixed up even and odd characters. Currently I cannot get it to compile. Bonus points if someone can show me how to loop the users input so after it asks the size to make the array, it prompts the user that many times for an "element" or word so that the function can scramble it and output it.
#include <stdio.h>
char transform(char str[]);
int main()
{ //Declare an array and size variable
int size = 0;
char str[size];
printf("How many elements?");
scanf("%d", &size);
printf("Please type an element: ");
//Get input from user
str[0] = scanf("%s", str);
transform(str);
printf("Please type another element: ");
//Get another input from user
str[1] = scanf("%s", str);
transform(str);
//This is the loop function that I programmed
char transform(char str[]);
{
//Loop that prints even characters
for (int i = 0; str[i] != '\0'; i++)
{
if(i % 2 == 0)
{
printf("%c", str[i]);
}
} //Space between even/odd characters
printf(" ");
//Loop that prints odd characters
for (int i = 0; str[i] != '\0'; i++)
{
if(i % 2 != 0)
{
printf("%c", str[i]);
}
}
printf("\n");
return 0;
}
}
#include <stdlib.h>
#include <stdio.h>
char transform(char str[]);
int main()
{ //Declare an array and size variable
int size = 0;
printf("How many elements?");
scanf("%d", &size);
for (int i = 0; i < size; ++i)
{
printf("Please type an element: ");
char str[2048]; //declare a wide buffer to be able to store lots of chars
scanf("%s", str);
transform(str);
}
return 0;
} //end your main here, by putting closing brace
char transform(char str[]) //define transform without semicolon, and outside of main
{ //This is the loop function that I programmed
//Loop that prints even characters
for (int i = 0; str[i] != '\0'; i++)
{
if (i % 2 == 0)
printf("%c", str[i]);
} //Space between even/odd characters
printf(" ");
//Loop that prints odd characters
for (int i = 0; str[i] != '\0'; i++)
{
if (i % 2 != 0)
printf("%c", str[i]);
}
printf("\n");
return 0;
}

Array changing its first letter without reason

I'm making a hangman and everything works fine if you win, but if you lose it doesn't print the word it was.
I was debugging it and I found that in one of the last iterations the first character is changed to '\000' so that is why it doesn't print, but I don't understand why because there is no line where the array word is changed.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#define VOCABULARY_SIZE 8
#define MAX_STRING 32
#define MAX_GUESS 6
int random_number(int a, int b)
{
return a + rand() % (b - a + 1);
}
int main()
{
//random word selection
srand((unsigned)time(NULL));
const char VOCABULARY[VOCABULARY_SIZE][MAX_STRING] = {"vehicle", "building", "shirt", "pencil", "batman", "dromedary", "peach", "hangman"};
char word[MAX_STRING];
int i;
i = random_number(0, VOCABULARY_SIZE - 1);
strcpy(word, VOCABULARY[i]);
//user word
int guesses = 0, length = strlen(word);
char letters[MAX_GUESS+1];
char input[MAX_STRING];
char temp_char;
char temp_input[MAX_STRING];
do
{
printf("\nYour entered letters are: ");
printf("%s", letters);
printf("\nYour letters found are: ");
for (int j = 0; j < length; j++)
{
if (word[j] == input[j])
{
printf("%c", word[j]);
}
else
{
printf("_");
}
}
printf("\n%d-letter word. %d out of %d failures. Enter a letter: ", length, guesses, MAX_GUESS);
scanf(" %c", &temp_char);
letters[guesses] = temp_char;
letters[guesses+1] = '\0';
for (int j = 0; j < length; j++)
{
if (word[j] == temp_char)
{
input[j] = word[j];
}
}
guesses++;
printf("\nWhat is the word to guess? ");
scanf(" %s", temp_input);
} while ((strcmp(input, word) != 0 && strcmp(temp_input, word) != 0) && guesses <= MAX_GUESS);
if (strcmp(input, word) == 0 || strcmp(temp_input, word) == 0)
{
printf("\nCongratulations, the word was %s!", word);
}
else
{
printf("\nBetter luck next time... The word was %s", word);
}
}
You're writing to letters out of bounds
char letters[MAX_GUESS+1];
int guesses = 0;
do {
//...
letters[guesses+1] = '\0'; // OOPS
//...
guesses++;
//...
} while (... && guesses <= MAX_GUESS);
Nicely written code, but errors in string management.
Initialize
First time printf("%s", letters); called, letters[] is junk. Initialize it.
// char letters[MAX_GUESS + 1];
char letters[MAX_GUESS + 1] = { 0 };
Too many guess
Off by 1, lower limit.
// ... && guesses <= MAX_GUESS);
... && guesses < MAX_GUESS);
Missing '\0'
strcmp(input, word) uses input as a string, yet it lacks a null character.
Flush
Best to insure output is seen before asking for input.
fflush(stdout); // add
scanf(" %c", &temp_char);
fflush(stdout); // add
scanf(" %s", temp_input);
Unbounded input
scanf(" %s", temp_input); is worse than gets(). Research fgets().
Perhaps more issues.

Maximum number of Characters in a character array

//Program to find max occurring character in string
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 100 // Maximum string size, change to make string smaller or larger
#define MAX_CHARS 255 // Maximum characters allowed for characters
void main()
{
char str[MAX_SIZE]; //store the string
int freq[MAX_CHARS]; // store frequency of each character
int i, max; // i is for loop max to store frequency
int ascii; //stores ascii value convertd from each char
char ch; //for choice
do{
clrscr();
i=0;
printf("\nEnter any string: ");
gets(str);
// Initializes frequency of all characters to 0
for(i=0; i<MAX_CHARS; i++)
{
freq[i] = 0;
}
// Finds occurance/frequency of each characters
i=0;
while(str[i] != '\0')
{
ascii = (int)str[i];
freq[ascii] += 1; //string's element is casted to int to store its ascii value for further comparision
i++;
}
// Finds maximum frequency of character
max = 0;
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] > freq[max])
max = i; //to print no. of times
}
printf("\nMaximum occurring character is '%c' = %d times.", max, freq[max]);
printf("\n Want to find again??(y/n):");
scanf("%c",&ch);
}while(ch=='Y'||ch=='y');
}
When I give it the input: "aaaaeeee", the output is "a" occurring 4 times, but "e" occurs 4 times too. I know this is sorted by ascii values and thats why it gives "a" as output, but what can I do in this program that the output gives both "a" and "e" as output when a case like this occurs?
Add max calculation ahead
i = 0;
max = 0;
while(str[i] != '\0')
{
ascii = (int)str[i];
freq[ascii] += 1;
if (freq[ascii] > max) max = freq[ascii]; // <==== here
i++;
}
Note that this is the max number of the same character you might have.
Then display all chars which maximum is equal to max
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] == max) printf("Character %c is at max %d\n", i, max);
}
To fix the endless loop, before the while add char c ; while ((c = getchar()) != EOF && c != '\n');
scanf("%c",&ch);
char c;
while ((c = getchar()) != EOF && c != '\n'); // <== note the ';'
} while(ch=='Y'||ch=='y');
Note that you shouldn't use gets, reason is explained here.
Whole code:
void main()
{
char str[MAX_SIZE]; //store the string
int freq[MAX_CHARS]; // store frequency of each character
int i, max; // i is for loop max to store frequency
int ascii; //stores ascii value convertd from each char
char ch; //for choice
do {
printf("\nEnter any string: ");
gets(str);
// Initializes frequency of all characters to 0
for(i=0; i<MAX_CHARS; i++)
{
freq[i] = 0;
}
// Finds occurance/frequency of each characters
for(i=0,max=0 ; str[i] != '\0' ; i++)
{
ascii = (int)str[i];
freq[ascii] += 1; //string's element is casted to int to store its ascii value for further comparision
if (freq[ascii] > max) max = freq[ascii];
}
for(i=0; i<MAX_CHARS; i++)
{
if(freq[i] == max) printf("Character %c is at max %d\n", i, max);
}
printf("\n Want to find again??(y/n):");
scanf("%c",&ch);
char c;
while ((c = getchar()) != EOF && c != '\n');
}while(ch=='Y'||ch=='y');
}
Above this line
printf("\nMaximum occurring character is '%c' = %d times.", max, freq[max]);
Delete it and add this code
for(i=0;i<MAX_CHARS;i++)
{
if(freq[i]==freq[max])
{
printf("\nMaximum occurring character is '%c' = %d times.", i, freq[i]);
}
}

Why is this reverse string program not working?

I am new to C programming so please do forgive my naivety. The following program when outputted fails to print the last character of the input string as the first character of the output string.
For example:
Enter no. of elements: 5
Enter string: hello
The reversed string is: lleh
Why is the o not printing?
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf("%d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf("%c", &string[i]);
}
printf("The reversed string is: ");
for (int i = (n - 1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
There is a side effect you take care of:
After scanf("%d", &n);, there is a pending newline in the input stream buffer.
When you later input n characters, scanf("%c", &string[i]) first reads the pending newline, then the n-1 first characters you type and the remainder of your input stays in the input buffer.
scanf() is a very clunky function. It is difficult to use properly.
Here is a way to fix your problem:
#include <stdio.h>
int main() {
char string[10000];
int i, n, c;
printf("Enter no. of elements: ");
if (scanf("%d", &n) != 1 || n < 0 || n > 10000)
return 1;
// read and discard pending input
while ((c = getchar()) != '\n' && c != EOF)
continue;
printf("Enter string: ");
for (i = 0; i < n; i++) {
if (scanf("%c", &string[i]) != 1)
break;
}
// the above loop could be replaced with a single call to fread:
// i = fread(string, 1, n, stdin);
printf("The reversed string is: ");
while (i-- > 0) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
Your scanf() should start with a space( more info about that ). Here is the code:
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf(" %d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf(" %c", &string[i]);
}
/* Just to be safer. */
string[n] = '\0';
printf("The reversed string is: ");
for (int i = (n-1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
Adding the space to the format string enables scanf to consume the
newline character from the input that happens everytime you press
return. Without the space, string[i] will receive the
char '\n'
So, merely one space is put before format specifier %c at line 11.
scanf(" %c", &string[i]);

How to calculate blank space

i have been trying calculate the amount of blank space in a sentence, but I don't know how to let the program know which sentence that I want it to calculate, please help me, here is my code.
#include <stdio.h>
#include <string.h>
#include <conio.h>
int wid, len, i, j, temp, blank;
char text[100], ch;
int main(){
printf ("Enter the width of the colum: ");
gets (text);
sscanf (text, "%d", &wid);
printf ("\nEnter a line of text: ");
gets (text);
len = strlen (text);
for (i = 0; i < 7; i++){
printf ("1234567890");
}
while(len > 50){
printf ("\nThe text is too long!\n");
break;
}
ch = getch();
for (j = 0; j < len; j++){
if (ch == ' ') {blank++;}
}
printf ("\n%d", blank);
}
I want to calculate how many blank for this part
printf ("\nEnter a line of text: ");
gets (text);
instead of
ch = getch();
for (j = 0; j < len; j++){
if (ch == ' ') {blank++;}
try
for(j = 0; j < len; j++)
{
if(text[j] == ' ') //comparing if the string in text contains blank space at position j
blank++;
}
also, instead of gets() to read the string, use fgets.
/* cprogram to count blanck spaces in the string*/
#include<stdio.h>
#include<string.h>
int main()
{
int len,i,blank_space=0;
char str[20];
printf("Enter the string ");
fgets(str,20,stdin);
printf("%s",str);
//claculate string length
len=strlen(str);
//printing length of the string
printf("length of the string is %d",len);
//loop to detect blankspaces
for(i=0;i<len;i++)
{
if(str[i]==' ')
blank_space++;
}
//display the result
printf("no of blanked spaces is %d",blank_space);
return 0;
}

Resources