So I have been taking classes on C and one of the exercises was to program a caesar cipher program that both encrypts and decrypts. And when the input is "ab cd", the output should be "de#fg" but instead it outputs "de?g?". So my guess is the spacebar messes everything up. But also another error was found when I inputted "a" and it outputted "d?ad?". Thanks in advance.
#include <stdio.h>
#include <string.h>
void cipher(char plain_str[], char cipher_str[]);
void decipher(char cipher_str[], char decipher_str[]);
int main() {
char plain_str[30];
char cipher_str[30];
char decipher_str[30];
printf("Enter plain string: ");
scanf("%s", plain_str);
cipher(plain_str, cipher_str);
decipher(cipher_str, decipher_str);
}
void cipher(char plain_str[], char cipher_str[]) {
int i = 0;
while(plain_str[i] != '\0') {
if((plain_str[i]+3) >= 0 && (plain_str[i]+3) <= 127) {
cipher_str[i] = plain_str[i] + 3;
} else {
cipher_str[i] = plain_str[i] - 124;
}
i++;
}
printf("%s\n", cipher_str);
}
void decipher(char cipher_str[], char decipher_str[]) {
//asdf
}
The %s operator in scanf only reads a single word, not a whole line. So if you enter ab cd, only ab is put into plain_str. To read a whole line, use fgets():
fgets(plain_str, sizeof(plain_str), stdin);
size_t len = strlen(plain_str);
if (plain_str[len-1] == '\n') {
plain_str[len-1] = '\0'; // Remove newline
}
The other problem is that you're never adding the null terminator to cipher_str, so you're printing whatever garbage is in it after the encoded characters. The simplest way to resolve this is to initialize it to an all-zero array when you declare the variable:
char cipher_str[30] = {0};
Related
I'm trying to write a program that uses Caesar's algorithm to cipher a string input. I'm a beginner to C but I can understand basic codes. So to cipher the text I wrote this code, but when I enter the input, I get an error that says
Segmentation fault (core dumped)
I tried to do some debugging by removing the else condition at the end and the program kind of worked for short inputs of 2-3 letters
Can someone please help me with this issue?
I'm using the CS50's header only to get the string in the first place.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char * argv[])
{
char name[] = "";
strcat(name, argv[1]);
int key = atoi(name);
string plaintext = get_string("plaintext: ");
int length = strlen(plaintext);
char ciphertext[] = "";
for(int i = 0; i < length; i++)
{
int skipCount = 0;
if(isalpha(plaintext[i]))
{
while(skipCount < key)
{
char tmp = (char) ((int) plaintext[i] + 1);
if(isalpha(tmp))
{
ciphertext[i] = tmp;
skipCount++;
}
else
{
if (isupper(plaintext[i]))
{
tmp = 'A';
skipCount++;
}
if (islower(plaintext[i]))
{
tmp = 'a';
skipCount++;
}
}
}
}
else ciphertext[i] = plaintext[i];
}
printf("%s\n", ciphertext);
}
What you need to understand about C, is that it does not automatically allocate memory.
You have to it your self!
This line:
char name[] = "";
creates an array of size 1, which holds a single character - the "null" character = '\0';
It signifies an empty string.
You can not copy any larger string in to it, because all strings in C must have a null character at the end, so there isn't enough room for even a single readable character.
As a beginner, you would need to decide what the maximum length of the string you want will be, and declare the array to be of proper size:
char name[255];
This is one example that can hold up to 254 characters, plus the terminating null character.
I'm building a program for reversing a string in visual studio, and while I run the code and enter a word I want to reverse, the program crashes.
#include <stdio.h>
#include <conio.h>
#include <string.h>
main(void) {
char r[256];
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(" %s", r, sizeof(r));
d = strlen(r);
for (i=d;i!=0;i--) {
printf("%s",i);
}
return 0;
}
Please note that I tried your program on Linux, so no MS Visual C++ and more specifically no conio.h and gets_s.
There are multiple problems with your program:
Your call to gets_s is incorrect, according to this and this, gets_s is defined as:
char *gets_s(
char *buffer,
size_t sizeInCharacters
);
You are calling it with illegal arguments. Instead of gets_s(" %s", r, sizeof(r)); you need to call it like this:
gets_s(r, 256);
the first parameter is pointer to the string buffer where the gets_s function will store the line from input and the second is the size of the buffer, note that in char r[256] you can store 255 characters and terminating zero (\0).
Your for loop is incorrect instead of for (i=d;i!=0;i--) { you need to do it like this:
for (i=d-1;i>=0;i--) {
now the loop starts from last character instead of \0 and ends when the i < 0 ie. the last print will be when i=0.
And your final mistake is that you are using printf incorrectly instead of printf("%s",i); you need to do:
printf("%c",r[i]);
because you are printing characters: "%c" is for char output and r[i] is i-th character from string r (don't forget that we count from 0).
So, in total this is how the program should look like:
#include <stdio.h>
#include <conio.h> // does not exist on GCC (Linux)
#include <string.h>
main(void) {
char r[256]; // 255 characters + \0
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(r, 256); // store at most 255 characters + \0
// does not work on GCC (Linux) even with -std=C11
d = strlen(r);
// start from last character and include first
for (i=d-1;i>=0;i--) {
// %c - character, r[i] gets the i-th character from string r
printf("%c",r[i]);
}
return 0;
}
void rev(char *s)
{
char *start, *end;
end = start + strlen(s) - 1;
for (start = s; end > start; ++start, --end) {
char tmp;
tmp = *start;
*start = *end;
*end = tmp;
}
}
Use the fgets function, and also put the reversing code in its own function, like I did. So the final code is
int main()
{
char line[80];
fgets(line, 80, stdin);
/* don't allow empty string */
if (*line == '\0') {
fprintf(stderr, "Empty string is not a string\n");
return 1;
}
/* remove the \n placed by fgets */
remnl(line);
rev(line);
printf("%s\n", line);
return 0;
}
void remnl(char *s) { s[strlen(s) - 1] = 0; }
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main(void) {
char r[256];
int i, d;
printf("\nEnter the word you want to reverse : ");
gets_s(r, sizeof(r));
d = strlen(r) - 1;
for (i = d; i >= 0; i--) {
printf("%c", r[i]);
}
_getch();
return 0;
}
I take user input using fgets() and store it into a temp array. I then concatenate that to a main array called userInput so that the user can enter multiple lines.
Let's say the user enters the following:
This is a sentence
This is a new line
I need it to print each line in the order they were entered but reverse the order of words like below:
sentence a is This
line new a is This
I have the current approach but I get this:
line
new a is sentence
This a is This
Below is my code where I call reversePrint() with a string to reverse:
void printToSpace(const char *str) {
do {
putc(*str, stdout);
} while(*str++ != ' ');
}
void reversePrint(const char *str) {
const char *p = strchr(str, ' ');
if (p == NULL) {
printf("%s", str);
}
else {
reversePrint(p + 1);
printToSpace(str);
}
}
Here is an alternative way:
#include <stdio.h>
#include <string.h>
void reversePrint(const char *str)
{
if (str)
{
reversePrint(strtok (NULL, " \t\n\r"));
printf("%s ", str);
}
}
int main(void)
{
char string[] = "This is a sentence";
reversePrint(strtok(string, " \t\n\r"));
return 0;
}
It seems so clear and simple that I suspect if strtok() is born for requirements like this.
Here are just a few thoughts...
I feel that using fgets will provide you with an undesired new-line marker. Hence, you need to handle the "\r\n" in the reverse printing function.
I feel that the reverse printing is easier to perform in a single function, although I loved the recursive approach, so I'll use it here.
I should point out that I wouldn't use a recursive function if this was a production application, as we'll be wasting resources and bloating the stack for no good reason.
On a non-recursive approach I would probably use the %.*s format, instead of printing each char separately.
I think your code would work if you only changed printToSpace so that it manages the \n contingency - but I felt like re-writinfg the function. Try this in your solution:
void printToSpace(const char *str) {
do {
putc(*str, stdout);
} while(*str && *str != '\n' && *str != '\r' && *str++ != ' ');
}
Here's my full code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_rev(char* str);
// collects two strings and send them to the `print_rev` function
int main(int argc, char const* argv[]) {
char str_array[2][255];
// Get string 1
printf("Enter the first string (up to 255 characters):\n");
fgets(str_array[0], 255, stdin);
printf("Please enter the second string (up to 255 characters):\n");
fgets(str_array[1], 255, stdin);
printf("You entered:\n1. %s2. %s", str_array[0], str_array[1]);
printf("\nString 1 reversed: ");
print_rev(str_array[0]);
printf("\nString 2 reversed: ");
print_rev(str_array[1]);
printf("\n");
}
// prints a string in reverse order.
void print_rev(char* str) {
// find the first occurrence of the ` ` (space)
char* p = strchr(str, ' ');
// if a space exists...
if (p) {
// call `print_rev` for whatever's after the space.
print_rev(p + 1);
// print a space
putc(' ', stdout);
}
// print every character until an EOL, space or NULL is encountered
while (*str && *str != ' ' && *str != '\n' && *str != '\r')
putc(*(str++), stdout);
}
#include <stdio.h>
#include <string.h>
#define MAX_LEN 100000
int main()
{
char str[MAX_LEN], temp[MAX_LEN];
printf("Enter the Sentence to print reverse : ");
scanf("%[^\n]%*c", &str);
int i, left, right, length = strlen(str);
left = 0;
right = length - 1;
printf("%d \n", length);
for(i=0;i<length;i++)
{
temp[i] = str[right];
right--;
}
printf("%s",temp);
return 0;
}
I'm trying to write a code that asks the user to enter a string and takes of all characters except the alphabetical.
Now i did it myself and it doesn't seem to work properly. I'm new to strings so i'm trying to understand and master strings. I tried to use gdb on mac but i don't have all the functions to understand this.
Could you please help?
What the code must do: User inputs (for example): h**#el(l)o&^w
and the output is hello.
here is my code:
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
int i;
int seen = 0;
printf("Enter String: ");
scanf("%s", string);
for (i=0; string[i]!='\0'; i++)
{
if (((string[i]<='a' || string[i]>'z')&&(string[i]<='A' || string[i]>'Z')) ||string[i]!='\0')
{
seen = 1;
}
else
seen = 0;
}
if (seen==0)
{
printf("%s", string);
}
}
well, your code has a couple of important problems:
you're not checking boundaries when iterating… what if I type in a 101 characters string? and a 4242 characters string?
next problem, is that scanf("%s", …) is considered dangerous, for the same reasons
so basically, what you'd want is to use fgets() instead of scanf().
But why not just get the input character by character, and build a string that has only the chars you want? It's simpler and flexible!
basically:
#include <ctype.h>
int main() {
char* string[100];
int i=0;
printf("Enter your string: ");
do {
// getting a character
char c = getchar();
// if the character is alpha
if (isalpha(c) != 0)
// we place the character to the current position and then increment the index
string[i++] = c;
// otherwise if c is a carriage return
else if (c == '\r') {
c = getchar(); // get rid of \n
// we end the string
string[i] = '\0'
}else if (c == '\n')
// we end the string
string[i] = '\0';
// while c is not a carriage return or i is not out of boundaries
} while (c != '\n' || i < 100);
// if we've got to the boundary, replace last character with end of string
if (i == 100)
string[i] = '\0';
// print out!
printf("Here's your stripped string: %s\n", string);
return 0;
}
I did not run it on my computer because it's getting late, so my apologies in case of mistakes.
Addendum:
wee the program skips my statement and shuts down
that's because your condition is inversed, and remove the \0 condition, as it will always happen with the scanf() that always append \0 to the string to end it. Try exchanging seen = 1 and seen = 0 or try using the following condition:
if ((string[i]>='a' && string[i]<='z')||(string[i]>='A' && string[i]<='Z')))
seen = 1;
else
seen = 0;
or simply, use ctypes's isalpha() function, like in our two examples!
No part(remove the extra characters) to change the string in your code.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char *filter(char *string, int (*test)(int)) {
char *from, *to;
for(to = from = string;*from;++from){
if(test(*from))
*to++ = *from;
}
*to = '\0';
return string;
}
int main(){
char string[100];
printf("Enter String: ");
scanf("%99s", string);
printf("%s\n", filter(string, isalpha));
return 0;
}
How can you code this in C language if the output is like this? I need strings format of the code because our topic is strings.
#include <stdio.h>
#include <stdlib.h>
void main()
{
char my_string[50];
printf("Enter a word:");
scanf("%s", my_string);
printf("Enter a word:");
scanf("%s", my_string);
// Some unknown code here...
// this part is my only problem to solve this.
getch();
}
Output:
Hello -> (user input)
World -> (user input)
HWeolrllod -> (result)
Okay, you need to do some investigating. We don't, as a general rule, do people's homework for them since:
it's cheating.
you'll probably get caught out if you copy verbatim.
it won't help you in the long run at all.
The C library call for user input that you should use is fgets, along the line of:
char buffer[100];
fgets (buffer, sizeof(buffer), stdin);
This will input a string into the character array called buffer.
If you do that with two different buffers, you'll have the strings in memory.
Then you need to create pointers to them and walk through the two strings outputting alternating characters. Pointers are not an easy subject but the following pseudo-code may help:
set p1 to address of first character in string s1
set p1 to address of first character in string s1
while contents of p1 are not end of string marker:
output contents of p1
add 1 to p1 (move to next character)
if contents of p2 are not end of string marker:
output contents of p2
add 1 to p2 (move to next character)
while contents of p2 are not end of string marker:
output contents of p2
add 1 to p2 (move to next character)
Translating that into C will take some work but the algorithm is solid. You just need to be aware that a character pointer can be defined with char *p1;, getting the contents of it is done with *p1 and advancing it is p = p + 1; or p1++;.
Short of writing the code for you (which I'm not going to do), there's probably not much else you need.
void main()
{
char my_string1[50],my_string2[50]; int ptr;
ptr=0;
printf("Enter a word : ");
scanf("%s",my_string1);
printf("enter a word");
scanf("%s",my_string2);
while(my_string1[ptr]!='\0' && my_string2[ptr]!='\0')
{
printf("%c%c",my_string1[ptr],my_string2[ptr]);
ptr++;
}
if(my_string1[ptr]!='\0')
{
while(my_string1[ptr]!='\0')
{ printf("%c",my_string1[ptr]);
ptr++;
}
}
else
{
while(my_string2[ptr]!='\0')
{printf("%c",my_string2[ptr]);
ptr++;
}
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
char my_string1[50],my_string2[50];
int i,l1=1,l2=0;
printf("Enter a word:");
scanf("%s", my_string1);
printf("Enter a word:");
scanf("%s", my_string2);
l1=strlen(my_string1); /* Length of 1st string */
l2=strlen(my_string2); /* Length of 2nd string */
if(l1==l2)
{
for(i=0;i<l1;i++)
{
printf("%c%c",my_string1[i],my_string2[i]);
}
}
else
{
printf("Length of the entered strings do not match");
}
}
This is your required code.
You can see that output needs to be a String containing all chars of User String1 and User String2 one by one...
You can do this like...
//add #include<String.h>
int l1=strlen(s1);
int l2=strlen(s2);
if(l1!=l2)
{
printf("length do not match");
return 0;
}
char ansstr[l1+l2];
int i,j=0,k=0;
for(i=0;i<l1+l2;i=i+2)
{
ansstr[i]=s1[j];
ansstr[i+1]=s2[k];
j++;
k++;``
}
//ansstr is your answer
Ok, here's your code. Come on guys, if he asked here it means he can't solve this.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char str1[] = "abcdefghijklmopq";
char str2[] = "jklm";
int len1 = strlen(str1);
int len2 = strlen(str2);
int c1 = 0, c2 = 0;
int max = (len1 > len2) ? len1 : len2 ;
char *result = malloc(len1 + len2);
for(c1 = 0; c1 <= max; c1++) {
if(c1 < len1)
result[c2++] = str1[c1];
if(c1 < len2)
result[c2++] = str2[c1];
}
result[c2] = 0;
printf("\n%s\n", result);
return 0;
}
Basically the loop picks up a character from str1 and appends it to result. Then it picks a character, which stands in the same position as the first from str2 and appends it to result, just as before. I increment c2 by 2 every time because I'm adding 2 chars to result. I check if c1 is bigger that the length of the strings because I want to copy only the characters in the string without the terminating \0. If you know that your strings have the same length you can omit these ifs.