Print a string till a particular character comes - c

I want the string to be printed till character ('e') comes.
Code which I tried:-
#include <stdio.h>
int main() {
int a,i,x;
char b[10];
char ch;
//enter input string
for(i=0;i<10;i++)
scanf("%c",&b[i]);
for(i=0;i<10;i++)
if(b[i]!='e')
printf("%c",b[i]);
return 0;
}
Input:abcdefghij
Actual output:abcdfghij
Desired output:abcd
Question : Where am I wrong ? Will putting a break inside if block work here?

This is much cleaner if you want to use scanf.
#include <stdio.h>
int main()
{
char b[101];
scanf("%100s", b);
printf("%s\n", b);
return(0);
}
Or even better.
#include <stdio.h>
#define MAX_LENGTH 100
int main()
{
char b[MAX_LENGTH+1]; // add 1 for the terminating zero
scanf("%100s", b);
printf("%s\n", b);
return(0);
}
This one uses fgets to read the entire line.
#include <stdio.h>
#define MAX_LENGTH 100
int main()
{
char b[MAX_LENGTH];
fgets(b, MAX_LENGTH, stdin);
printf("%s", b);
return(0);
}

How to print a string till limit?
What code should do is use fgets().
Avoid using scanf(). Is is too easy to use wrong.
#include <stdio.h>
#include <string.h>
int main() {
char b[100];
if (fgets(b, sizeof b, stdin)) {
// If code needs to lop off the potential \n at the end
b[strcspn(b, "\n")] = '\0';
printf("%s\n", b);
}
return 0;
}
Advanced issues include how to handle excessively long input lines and error handling - not shown here.

Here is what you need to do
#include <stdio.h>
int main()
{
int a,i,x;
char b[10];
char ch;
//enter input string
for(i=0;i<10;i++)
{
scanf("%c",&b[i]);
}
for(i=0;i<10;i++)
{
if(b[i]=='e')
{
break;
}
}
return 0;
}
re

There are several mistakes!
If you are initializing your loops from 0 then you need to set the condition till i<100.
Change your format specifiers to %s.
Change your IF statement to if(b[i]!='\0').

#include <stdio.h>
int main()
{
int i;
char b[10];
for(i=0;i<10;i++)
{
scanf("%c",&b[i]);
}
for(i=0;i<10;i++)
{
if(b[i]=='e')
{
break;
}
printf("%c",b[i]);
}
return 0;
}

Related

Why cant the loop be terminated in my code?

This a reverse string code but the loop cant be terminated and keeps taking input
How can I terminate it
#include <stdio.h>
#include <string.h>
#define len 100
int main() {
char str[len];
int i;
do {
gets(str);
for (i = (strlen(str) - 1); i > -1; i--) {
printf("%c", str[i]);
}
printf("\n");
} while (str[0] != '\0');
return 0;
add str[0]='\0'; before gets and its done. this is because making a loop termination and to get out of the loop after clicking enter.
#include <stdio.h>
#include <string.h>
#define len 100
int main() {
char str[len];
int i,lenh;
do{
str[0]='\0';
gets(str);
lenh=strlen(str);
for(i=lenh-1;i>=0;i--)
{
printf("%c",str[i]);
}
printf("\n");
}while(str[0]!='\0');
return 0;
}
now, there are a few points (answer code below)
Basically, you are printing hand-to-hand with input, while the question states of a multi line input. So, first you have to take all the inputs and then output will be shown.
Your original code does not keep taking input as you have said. Question says the last string is empty string. You press enter in empty string, your above code will terminate.
Remember Last Input String Should be Empty, that's termination condition
#include <stdio.h>
#include <string.h>
int main(){
char str[100];
char stringArray[50][100]={0};
int k,m,count=0,i=0,j=0;
do {
fgets(str,100,stdin);
k=strlen(str);
for(m=0;m<k-1;m++){
stringArray[count][k-m-2]=str[m];
}
count++;
}
while (str[0] != '\n');
for(i=0; i<count; i++){
for(j=0;stringArray[i][j]!=0;j++){
printf("%c",stringArray[i][j]);
}
if(i<count-1){
printf("\n");}
}
return 0;
}
sample input
Hello team Loop
Welcome
sample output
pooL maet olleH
emocleW

Mono alphabetic cipher doesnt work correctly

Here is my code. Substitution Cipher in C. But i got an error this line: char *encryption (char cipher_text[]) { function definition is not allowed here. I think probably "main" function place not right. How can i fix it?
And by the way how can i generate random alphabet for this code? Thank you so much.
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>
#include <string.h>
char *encryption (char cipher_text[]) {
int i, val, j;
printf("\n abcdefghijklmnopqrstuvwxyz \n");
You cannot define a function inside another one. encryption is defined in main :/
In C, you cannot declare a function inside another function, like you did.
Here is your code that will compile:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <ctype.h>
#include <string.h>
char *encryption (char []);
void *decryption (char []);
char alpha [26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
char key[26];
char *encryption (char cipher_text[]) {
int i, val, j;
printf("enter the unique KEY of 26 character:");
scanf("%s", key);
printf("\n abcdefghijklmnopqrstuvwxyz \n");
printf ("%s", key);
for (i=0; i <strlen(cipher_text); i++)
{
for (j=0; j<26; j++)
{
if (alpha[j]== cipher_text[i]) {
cipher_text[i]=key[j];
break;
}
}
}
printf ("your message enc: %s", cipher_text);
return cipher_text;
}
int main ()
{
int i, key, choice, flag=0;
char *c_text, msg[255];
printf("\n Enter plain text:");
scanf ("%[^\n]", msg);
encryption(msg);
return 0;
}
How to generate random characters is answered here.

Setting last character in a string to 0 causes program crash

This is for a homework assignment, so it can not use loops of any kind as a way to force recursion practice. I am also not to change the method signature, or anything in the main() function.
The function is intended to use recursion to print a string in reverse. I learned on this site (Strip first and last character from C string) how to remove the last character in a string. When I try and reproduce it in my code, the program crashes on execution. Here is that code:
#include <stdio.h>
#include <string.h>
void print_reverse_str(char *str) {
if (strlen(str) == 1)
printf("%c", &str[0]);
else {
int len = strlen(str);
int lastIndex = len - 1;
char endChar = str[lastIndex];
printf("%c", &endChar);
str[lastIndex] = 0;
print_reverse_str(str);
}
}
int main() {
print_reverse_str("My string");
printf("\n");
print_reverse_str("!ti tog uoy ,siht daer nac uoy fI");
printf("\n");
}
You can not change a string literal.
Character display with printf. E.g printf("%c", character);, not &character
try this.
#include <stdio.h>
#include <string.h>
void print_reverse_str(char *str){
if (*str){
print_reverse_str(str+1);
printf("%c", *str);
}
}
int main(){
print_reverse_str("My string");
printf("\n");
print_reverse_str("!ti tog uoy ,siht daer nac uoy fI");
printf("\n");
}

Program crashing, can't explain why?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int compare(char word[], char mystery[])
{
int i=0;int bool=1;
while((i<=20)&&(bool==1))
{
if (word[i]==mystery[i])
i++;
else
bool=0;
}
return bool;
}
char readCharacter()
{
char character = 0;
character = getchar();
character = toupper(character);
while (getchar() != '\n') ;
return character;
}
void readString(char *word,char *mystery)
{
int i=0;
printf("Enter the word to guess : ");
scanf("%s",word);
while(*((word)+(i)) != '\0')
{
*((word)+(i))= toupper(*(word+i));
*((mystery)+(i))='*';
i++;
}
*(mystery+i)='\0';
}
void process(char *word,char *mystery,char letter,int *change)
{
int i=0;
while (*((word)+(i))!= '\0')
{
if (*((word)+(i))==letter)
{
*((mystery)+(i))=letter;
*change=1;
}
i++;
}
}
void test(char *word,char *mystery, int triesleft)
{
if (*mystery!=*word)
{
printf("The mystery word is : %s",*mystery);
printf("\n You have %d tries left.", triesleft);
}
else
{
printf("You won !");
}
}
int main()
{
int triesleft = 10; int change=0;
char word[20]; char mystery[20];char letter;
readString(&word,&mystery);
while((compare(word,mystery)==0) && (triesleft>0))
{
change=0;
printf("Enter the letter :");
letter=readCharacter();
process(&word,&mystery,letter,&change);
if ((change)==1)
triesleft--;
test(&word,&mystery,triesleft);
}
if (triesleft>0)
return 0;
printf("You lost.");
return 1;
}
I'm a beginner in C and I wanted to code a simple Hangman game in C and it compiled fine but it seems to crash after entering the first letter and I can't find a solution !
I don't know what may be the cause but I had a lot of trouble using strings in C, as they don't exist maybe it was a bad manipulation of that I don't know :/
You first call to readString is enough to crash the program.
word and mystery are arrays, so &word is a char ** not a char *. You should use
readString(word, mystery);
But compiler should have issue a warning on that. Warning are not there to distract beginners to to denote possible (probable if you do not understand the warning) mistakes.
There are probably other problems later ...
In the readString() function, you should use '\0' instead of NULL, as C strings are ended with this character.
You cannot declare a variable named bool as it is a type. In C, it is not actually defined for all compilers as bool is not part of the standard but some compilers and some platform will define it anyway

What's wrong with this simple C code?

#include <stdio.h>
int main()
{
int m,n; scanf("%d %d",&m,&n);
char ar[m][n];
char buf[n];
int a,b;
for(a=0;a<m;a++)
{
gets(buf);
for(b=0;b<n;b++) ar[a][b] = buf[b];
}
for(a=0;a<m;a++,printf("\n")) for(b=0;b<n;b++) printf("%c",ar[a][b]);
return 0;
}
This code takes m lines as input from stdin, each line containing n characters, and prints all the lines to stdout. Simple as that. But there seems to be a memory leak, because the first time gets(buf) is encountered, its execution is skipped.
I tried it in C++ too, thinking the memory leak will disappear. Here is the code:
#include <cstdio>
using namespace std;
int main()
{
int m,n; scanf("%d %d",&m,&n);
char **ar = new char*[m];
char *buf = new char[n];
int a,b;
for(a=0;a<m;a++)
{
gets(buf);
ar[a] = new char[n];
for(b=0;b<n;b++) ar[a][b] = buf[b];
}
for(a=0;a<m;a++,printf("\n")) for(b=0;b<n;b++) printf("%c",ar[a][b]);
return 0;
}
But it is behaving exactly the same.
Here is some sample input and output:
2 3
abc
def
output:
x��
abc
GDB doesn't seem to show anything up too. Please help..
It's not a "memory leak". The problem is that the first gets() call reads the newline from when you enter the two dimensions on the first line; it puts zero characters into the buffer, but you print 5, which is why you get a line of garbage.
Add a "\n" at the end of the scanf() format string so scanf() consumes the newline, and your program will work perfectly. Note that gets() is terribly unsafe; using fgets(buf, n, stdin) is much preferred.
In addition to missing '\n' in scanf() you should allocate more space for buf:
Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m,n;
if(scanf("%d%d\n",&m,&n) != 2)
exit(EXIT_FAILURE);
char ar[m][n];
char buf[n+2]; // '\n\0'
int a,b;
for(a=0;a<m;a++)
{
if (!fgets(buf, n+2, stdin)) exit(EXIT_FAILURE);
for(b=0;b<n;b++) ar[a][b] = buf[b];
}
for(a=0;a<m;a++,printf("\n")) for(b=0;b<n;b++) printf("%c",ar[a][b]);
return 0;
}
Output
abc
def

Resources