I am trying to create a program that can modify a text according to the user key. It seems to work well, until I input something and it adds extra things.
For example, if I add the word hello and a key of 3, it says khoor plus some extra weird characters. Can you tell me please what is the problem? Thank you very much.
#include <stdio.h>
#include <ctype.h>
#define MAXSIZE 100
void encrypt(senTence[], int key);
int main(void)
{
int userKey;
char sentence[MAXSIZE];
printf("Input the text that you want to encrypt:\n> ");
fgets(sentence, 99, stdin);
// printf("\nThe string that you wrote is:\n%s\n\n", sentence);
printf("Input the key:\n");
scanf("%d", &userKey);
//printf("\nThe key that you selected is: %d\n\n", userKey);
encrypt(sentence, userKey);
return 0;
}
void encrypt(const char senTence[], int key)
{
int i = 0;
char q[MAXSIZE];
for(i = 0; senTence[i] != '\0'; ++i)
{
if( ( isupper(senTence[i]) ) || ( islower(senTence[i]) ) )
{
q[i] = senTence[i] + (char)key;
}
else
{
q[i] = (senTence[i]);
}
}
printf("%s", q);
}
You didn't terminate the result string q in encrypt().
Add the following line before printf().
q[i] = '\0';
Another way is initialize q to all-zero:
char q[MAXSIZE] = {0};
You forgot to null terminate your array q, so using as a string will not be possible.
After you have performed the required operation on all the elements of the senTence and stored it to q, you need to null terminate q.
Use
q[i] = '\0';
printf("%s\n", q);
I ran the code, was giving a few warnings and an error, related to the function prototype. I fixed that and it is working fine now!
#include <stdio.h>
#include <ctype.h>
#define MAXSIZE 100
void encrypt(const char senTence[], int key);
int main(void)
{
int userKey;
char sentence[MAXSIZE];
printf("Input the text that you want to encrypt:\n> ");
fgets(sentence, 99, stdin);
// printf("\nThe string that you wrote is:\n%s\n\n", sentence);
printf("Input the key:\n");
scanf("%d", &userKey);
//printf("\nThe key that you selected is: %d\n\n", userKey);
encrypt(sentence, userKey);
return 0;
}
void encrypt(const char senTence[], int key)
{
int i = 0;
char q[MAXSIZE];
for(i = 0; senTence[i] != '\0'; ++i)
{
if( ( isupper(senTence[i]) ) || ( islower(senTence[i]) ) )
{
q[i] = senTence[i] + (char)key;
}
else
{
q[i] = (senTence[i]);
}
}
printf("%s", q);
}
Related
After i put a name in the terminal and it is shorter, then 20 chars, it wants inputs until i have filled all the 20 positions in the array.
I know it is because of the for cycle i have there, but I don't know how else to fill that end of the array with nothing("").
In the array there is for example this "Helloworld\n123\n123"
Thank you for help in advance.
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
main(void) {
char name[NAME] = {""};
malloc(sizeof(name[NAME]));
printf("Choose your name: ");
for (int i = 0; i < NAME; i++) {
scanf("%c", &name[i]);
}
//Welcome and the name
printf("Welcome: ");
for (int i = 0; i < NAME; i++) {
printf("%c", name[i]);
}
return 0;
}
You need to stop reading at a newline (+should also check return codes).
A loop like:
size_t i=0;
for (; i < sizeof(name)-1; i++) {
if (1==(scanf("%c",&name[i]))){ if (name[i]=='\n') break; }
else if (feof(stdin)) break; //end of file?
else return perror("getchar"),1; //report error
}
name[i]='\0';
will achieve that (can also use getchar/getc/fgetc instead of scanf)
or you can use fgets:
if(NULL==fgets(name,sizeof(name),stdin)) return perror("fgets"),1;
//erase a possibly included newline at the end
//(won't be there if you pressed Ctrl+D twice rather than
//Enter to submit your input or if you're at the end of
//a stdin redirected from a file)
size_t len = strlen(name);
if(name[len-1]=='\n') name[len-1]='\0';
Whole program with both versions (in the if(0){...}else{...}) :
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(void) {
char name[NAME] = {""};
//malloc(sizeof(name[NAME])); //a useless memory leak; don't do this!
printf("Choose your name: ");
if(0){
if(NULL==fgets(name,sizeof(name),stdin)) return perror("fgets"),1;
size_t len = strlen(name);
if(name[len-1]=='\n') name[len-1]='\0';
}else{
size_t i=0;
for (; i < sizeof(name)-1; i++) {
if (1==(scanf("%c",&name[i]))){ if (name[i]=='\n') break; }
else if (feof(stdin)) break; //end of file?
else return perror("getchar"),1;
}
name[i]='\0';
}
//Welcome and the name
printf("Welcome: ");
for (int i = 0; i < NAME; i++) {
printf("%c", name[i]);
}
return 0;
}
If you have to use scanf and %c format:
char *readLineUsingCharAndScanf(char *buff, size_t size, FILE *fi)
{
char ch;
char *wrk = buff;
while(size-- && fscanf(fi, "%c", &ch) == 1 && ch != '\n' ) *wrk++ = ch;
*wrk = 0;
return buff;
}
void dumpString(const char *restrict str, size_t size)
{
while(*str && size--)
{
printf("%03d [0x%02x] - %s\n", *str, *str, (*str >= 32 & *str <= 127) ? (char[]){'\'', *str, '\'', 0} : "not printable");
str++;
}
}
int main(void)
{
char name[20];
dumpString(readLineUsingCharAndScanf(name, 19, stdin), 20);
}
https://godbolt.org/z/vWvP68TbW
scanf() is not the best tool for your purpose. Here is a simple and safe solution:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define NAME 20
int main(void) {
char name[NAME];
int c;
size_t i;
printf("Enter your name: ");
i = 0;
while ((c = getchar()) != EOF && c != '\n') {
if (i < sizeof(name) - 1)
name[i++] = c;
}
name[i] = '\0';
//Welcome and the name
printf("Welcome: %s\n", name);
return 0;
}
If you must use scanf(), use this:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#define NAME 20
int main(void) {
char name[NAME];
char c;
size_t i;
printf("Enter your name: ");
i = 0;
while (scanf("%c", &c) == 1 && c != '\n') {
if (i < sizeof(name) - 1)
name[i++] = c;
}
name[i] = '\0';
//Welcome and the name
printf("Welcome: %s\n", name);
return 0;
}
Thank you everyone for answering. Unfortunately the first two answers are too complicated for me yet. And the third one was not working properly.
But I found the simplest answer. :) Many thanks
#include <stdio.h>
int main(void)
{
char name[20];
printf("Choose your name: ");
scanf("%[^\n]*c",name);
printf("My name is %s",name);
}
For your needs I would use scanf with the string conversion specifier %s. In this case, the input name would be read and stored character by character in the buffer until the whitespace would be read. Here is the code.
#define NAME 20
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char name[NAME] = {""};
malloc(sizeof(name[NAME]));
printf("Choose your name: ");
scanf("%s", &name);
printf("%s", &name);
return 0;
}
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;
}
My program in C which is Palindrome has an error in its function. My function is not comparing the 2 characters in my string. When I type a single character it answers palindrome but if it is two or more always not palindrome.
Code:
int IntStrlength=strlen(StrWord);
int IntCtr2=0;
int IntCtr=1, IntAnswer;
while(IntCtr<=(IntStrlength/2)){
printf(" %d %d\n", IntCtr2,IntStrlength);
if(StrWord[IntStrlength] != StrWord[IntCtr2]){
IntAnswer=0;
printf(" %d=Not Palindrome", IntAnswer);
exit (0);
}//if(StrWord[IntCtr2]!=StrWord[IntStrlength]) <---------
else{
IntCtr2++;
IntStrlength--;
}// else <--------
IntCtr++;
}//while(IntCtr<IntStrlength/2) <-----------
IntAnswer=1;
printf(" %d=Palindrome", IntAnswer);
return ;
}
Single character:
Two or more characters:
Why not write it like this
int wordLength = strlen(StrWord);
for (int i=0;i<(wordLength/2);i++) {
if (StrWord[i] != StrWord[wordLength-i-1]) {
return 0;
}
}
return 1;
For words with an even length (say 8) the counter will go from 0 to 3, accessing all letters. For uneven words (say 7) the c ounter will go from 0 to 2, leaving the middle element unchecked. This is not necessary since its a palindrome and it always matches itself
#include<stdio.h>
int check_palindrom(char *);
int main()
{
char s1[20];
printf("Enter the string...\n");
gets(s1);
int x;
x=check_palindrom(s1);
x?printf("Palindrom\n"):printf("Not Palindrom\n");
}
int check_palindrom(char *s)
{
int i,j;
for(i=0;s[i];i++);
for(i=i-1,j=0;i>j;i--,j++)
if(s[i]!=s[j])
return 0;
if(s[i]==s[j])
return 1;
}
Enter the string...
radar
Palindrom
I've seen this algorithm before in a interview book called "Cracking the Coding Interview".
In it the author shows a very simple and easy implementation of the code. The code is below: Also here is a video explaining the code.
#include<stdio.h>
#include<string.h> // strlen()
void isPalindrome(char str[]);
int main(){
isPalindrome("MOM");
isPalindrome("M");
return 0;
}
void isPalindrome(char str[]){
int lm = 0;//left most index
int rm = strlen(str) - 1;//right most index
while(rm > lm){
if(str[lm++] != str[rm--]){
printf("No, %s is NOT a palindrome \n", str);
return;
}
}
printf("Yes, %s is a palindrome because the word reversed is the same \n", str);
}
You can do this like this:
#include <stdio.h>
#include <string.h>
int check_palindrome(char string []);
int main()
{
char string[20];
printf("Enter the string...\n");
scanf ("%s", &string);
int check;
check = check_palindrome (string);
if (check == 0)
printf ("Not Palindrome\n");
else
printf ("Palindrome\n");
return 0;
}
int check_palindrome (char string [])
{
char duplicate [];
strcpy (string, duplicate);
strrev (string);
if (strcmp (string, duplicate) == 0)
return 1;
else
return 0;
}
This uses the strcmp and strrev function.
Take a look at this code, that's how I have implemented it (remember to #include <stdbool.h> or it will not work):
for(i = 0; i < string_length; i++)
{
if(sentence[i] == sentence[string_lenght-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
Doing that it will check if your sentence is palindrome and, at the first occurence this is not true it will break the for loop. You can use something like
if(palindrome)
printf(..);
else
printf(..);
for a simple prompt for the user.
Example :
radar is palindrome
abba is palindrome
abcabc is not palindrome
Please , pay attention to the fact that
Abba
is not recognized as a palindrome due to the fact that ' A ' and 'a' have different ASCII codes :
'A' has the value of 65
'a' has the value of 97
according to the ASCII table. You can find out more here.
You can avoid this issue trasforming all the characters of the string to lower case characters.
You can do this including the <ctype.h> library and calling the function int tolower(int c); like that :
for ( ; *p; ++p) *p = tolower(*p);
or
for(int i = 0; str[i]; i++){
str[i] = tolower(str[i]);
}
Code by Earlz, take a look at this Q&A to look deeper into that.
EDIT : I made a simple program to do this, see if it can help you
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <ctype.h>
void LowerCharacters(char *word, int word_lenth);
int main(void){
char *word = (char *) malloc(10);
bool palindrome = false;
if(word == 0)
{
printf("\nERROR : Out of memory.\n\n");
return 1;
}
printf("\nEnter a word to check if it is palindrome or not : ");
scanf("%s", word);
int word_length = strlen(word);
LowerCharacters(word,word_length);
for(int i = 0; i < word_length; i++)
{
if(word[i] == word[word_length-1-i])
palindrome = true;
else
{
palindrome = false;
break;
}
}
palindrome ? printf("\nThe word %s is palindrome.\n\n", word) : printf("\nThe word %s is not palindrome.\n\n", word);
free(word);
return 0;
}
void LowerCharacters(char *word, int word_length){
for(int i = 0; i < word_length; i++)
word[i] = tolower(word[i]);
}
Input :
Enter a word to check if it is palindrome or not : RadaR
Output :
The word radar is palindrome.
This code may help you to understand the concept:
#include<stdio.h>
int main()
{
char str[50];
int i,j,flag=1;
printf("Enter the string");
gets(str);
for(i=0;str[i]!='\0';i++);
for(i=i-1,j=0;j<i;j++,i--)
{
str[i]=str[i]+str[j];
str[j]=str[i]-str[j];
str[i]=str[i]-str[j];
}
for(i=0;str[i]!='\0';i++);
for(i=i-1,j=0;j<i;j++,i--)
{
if(str[i]==str[j]){
flag=0;
break;
}
}if(flag==0)
{
printf("Palindrome");
}else
{
printf("Not Palindrome");
}
}
I have solution for this
char a[]="abbba";
int i,j,b=strlen(a),flag=0;
for(i=0,j=0; i<b; i++,j++)
{
if(a[i]!=a[b-j-1])
{
flag=1;
break;
}
}
if(flag)
{
printf("the string is not palindrum");
}
else
{
printf("the string is palindrum");
}
This may works for you
#include <stdio.h>
#include <stdlib.h>
int main(void) {
setbuf(stdout,NULL);
int i,limit;
char string1[10];
int flag=0;
printf("enter a string");
scanf("%s",string1);
limit=strlen(string1);
for(i=0;i<limit;i++){
if(string1[i]!=string1[limit-i-1]){
flag=1;
break;
}
} if(flag==1){
printf("entered string is not palindrome");
}else{
printf("entered string is palindrome");
}
return EXIT_SUCCESS;
}
I've got an assignment from school to make a program that will encrypt and decrypt a text. I have to use this declaration:
int encrypted(char *plainText, int arrLength, int key, char *cipherText);
For the moment i can make the caesar cipher work when i have the for-loop (the one i show in myfunctions.c) in main.c, but when i write the for-loop in another file (myfunctions.c) with the declaration above, it compiles and runs, but it seems like the for-loop in myfunctions.c doesn't executes like it should.
Here is my main.c:
#include <stdio.h>
#include <string.h>
#include "myfunctions.h"
int main(){
int key, arrLength, menu=0;
char plainText[100], cipherText[100], result[100];
printf("Encrypt\n");
printf("Enter your key (1-25): ");
scanf("%d", &key);
printf("Write the word or sentece you want to encrypt: ");
fgets(plainText, 100, stdin);
arrLength=strlen(plainText);
encrypted(plainText, arrLength, key, result);
getchar();
return 0;
}
myfunctions.c:
#include "myfunctions.h"
#include <stdio.h>
#include <string.h>
int encrypted(char *plainText, int arrLength, int key, char *cipherText){
int result = 0;
for(int i = 0; i < arrLength; i++)
{
// encryption
result = (*plainText + key);
// wrapping after Z for uppercase letters
if (isupper(*plainText) && (result > 'Z'))
{
result = (result - 26);
}
// wrapping after z for lowercase letters
if (islower(*plainText) && (result > 'z'))
{
result = (result - 26);
}
if (isalpha(*plainText))
{
printf("%c", result);
}
else
{
printf("%c", *plainText);
}
}
return 1;
}
myfunctions.h
#ifndef myfunctions_h
#define myfunctions_h
int encrypted(char *plainText, int arrLength, int key, char *cipherText);
#endif
You forgot to inclement plainText in the for loop in encrypted().
Be careful not to have fgets() read newline character before the plain text.
Try this main function
int main(){
int key, arrLength, menu=0;
char keyText[100],plainText[100], cipherText[100], result[100];
printf("Encrypt\n");
printf("Enter your key (1-25): ");
fgets(keyText, 100, stdin);
sscanf(keyText, "%d", &key);
printf("Write the word or sentece you want to encrypt: ");
fgets(plainText, 100, stdin);
arrLength=strlen(plainText);
encrypted(plainText, arrLength, key, result);
return 0;
}
and changing the loop for(int i = 0; i < arrLength; i++)
to for(int i = 0; i < arrLength; i++, plainText++)
So I made a program where I have to input a word and it displays if it is a palindrome (a word that is the same both ways) or not.
#include <stdio.h>
#include <string.h>
int main(int argc, const char * argv[]){
char word;
int length, counter;
printf("Please enter a word: ");
scanf("%c", &word);
int flag = 1;
for (counter = 0; counter < length && flag; counter++) {
printf("%c\t %c", word[counter], word[length - counter])
if (word[counter] == word[length - counter - 1]){
flag = 0;
}
}
if (flag) {
printf("%c is a palindrome!", word);
}
else {
printf("%c is NOT a palindrome!", word);
}
}
I set it up so that it displays each letter side by side. If a letter isn't the same then the flag is "thrown"(set to 0) and this will end the program saying: "word is NOT a palindrome!"
I get an error at the part where it says word[counter] saying it isn't a subscripted value. What can I do to make this work? Is there anything else I am doing wrong?
This char word; is not an array. This char word[100]; is an Array. Also you read a single character using scanf("%c", &word); not a word (as in a string or series of characters). Use:
fgets (word , 100 , stdin)
Also length is not initialized, so it will lead to UB.
Make this modifications in your program.It will run fine.
#include <stdio.h>
#include <string.h>
int main()
{
char word[100];
int length, counter;
printf("Please enter a word: ");
scanf("%s",word);
length=strlen(word);
int flag = 1;
for(counter = 0; counter < length/2 && flag; counter++)
{
if (word[counter] != word[length-counter-1])
{
flag = 0;
break;
}
}
if (flag)
{
printf("%s is a palindrome!\n", word);
}
else {
printf("%s is NOT a palindrome\n!", word);
}
}
****************************************************************
* Simple Array Palindrome Program *
****************************************************************/
#include <iostream>
using namespace std;
int main (){
int arr_size;
int flag=0;
/*****************************************
* Array Size *
*****************************************/
cout<<"Enter The Array Size: \n->arr[";
cin>>arr_size;cout<<" ]";
int arr[arr_size];
/*****************************************
* User_Input *
*****************************************/
for(int i=0;i<arr_size;i++){
cout<<"Enter Value For Arr[ "<<i<<" ] -> ";
cin>>arr[i];
}
/*****************************************
* Palindrome_Check *
*****************************************/
for(int k=0,j=arr_size-1;k<arr_size && j>-1;k++)
{
if(arr[i]==arr[j];
{
flag++;
}
}
/*****************************************
* Flag Check *
*****************************************/
if(flag==arr_size) {
cout<<"Array Is Palindrome: ";
}
else
{
cout<<"Array Is Not Palindrome: ";
}
}