I've tried to make a code that encrypts a message in ROT13, i'll leave here the whole code.
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<ctype.h>
#include<locale.h>
#include<string.h>
#define MAX 500
int main(){
int i,diff[i];
char string[MAX];
printf("\x1b[34mHello friend,this is a simple ROT13 decryption algorhytm brought to you by #NikoScaccia\x1b[0m\n");
printf("\x1b[31mPlease Enjoy!!!\x1b[0m\n");
printf("\n");
printf(">>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<\n");
printf("\n");
printf("Insert a phrase: \n");
printf("\x1b[0,35mMAX LEN: %d\x1b[0m\n",MAX);
scanf("%99[^\n]",string);
for(i=0;i<'\0';i++){
if(string[i]<='a' && string[i]<='z' || string[i]>='A' && string[i]<='Z'||!isspace(string[i])){
string[i]=tolower(string[i]);
}
else {
printf("Invalid Input!\n");
exit(EXIT_FAILURE);
}
}
for(i=0;i<strlen(string);i++){
if(string[i]!=' '){
if((int)string[i]+13<=122){
string[i]=(int)string[i]+13;
}
else {
if(string[i]!='n'){
diff[i]=122-(int)string[i];
string[i]=(int)string[i]+diff[i];
string[i]= (int)string[i]-26+13-diff[i];
}
}
}
}
printf("Encrypting...\n");
printf("Encrypted message: %s\n",string);
return 0;
}
the code compiles correctly but it has two main problems,it seems to translate correctly every letter in the alphabet except for the letter 'n' which for some reason translates to '{',
also if I try to feed the program something like "hello man" it executes correctly(except obviously for the letter n),while if for example I try "hello friend" i get a segmentation fault error.
Can someone help me with this?
Thank you in advance.
At least these problems:
Uninitialized i
i is not known when diff[i] is defined. Array size unknown, potentially invalid.
int i,diff[i]; // Bad
Do not define diff[] until after i is assigned.
Define diff[] after the for(i=0; string[i]; i++){...} loop below.
Wrong compare
Loop never iterates.
// for(i=0;i<'\0';i++){
for(i=0; string[i]; i++){
Wrong compare
<= vs. >=
//string[i]<='a' && string[i]<='z'
string[i]>='a' && string[i]<='z'
Unneeded compare
Why test string[i] is not a space?
// if(... || !isspace(string[i])) {
if(...){
Simplification
Tests not needed.
// for(i=0;i<'\0';i++){
// if(string[i]<='a' && string[i]<='z' || string[i]>='A' && string[i]<='Z'||!isspace(string[i])){
// string[i]=tolower(string[i]);
//}
for(i=0; string[i]; i++){
string[i]=tolower((unsigned char) string[i]);
}
int diff[i]; // Now define `diff[]`
Related
#include<stdio.h>
int main() {
char text[1000];
int ch;
int index = 0;
while ((ch = getchar()) != EOF) {
text[index] = ch;
index++;
}
text[index] = '\0';
int i =0;
int num_Count=0;
int lower_Count=0;
int upper_Count =0;
while(i < index) {
if((text[i]>='0') && (text[i]<='9')){
num_Count ++;
i++;
}
else if((text[i]>='A') && (text[i]<='Z')){
upper_Count++;
i++;
}
else if((text[i]>='a') && (text[i] <='z')){
lower_Count++;
i++;
}
else
i++;
}
printf("%d %d %d", num_Count, lower_Count, upper_Count);
return 0;
}
It is a program that outputs the number of lower case, upper case, and number when the sentence is inputted.
For example,
Hi
Name
100
Would output 3 4 2
I keep seeing a runtime error.
The (while) part seems to be wrong.. I do not know what's wrong.
I ran your code in my system and checked for the input: Hi Name 100. The output I got is 3 4 2 which is the expected output. I feel the only place where the code can run in an infinite loop is while reading the inputs. Try to use ctrl+ d for EOF or ctrl+ z for windows.
Rest every thing is fine.
EOF means End Of File. It is used when you read data from a file. I suggest put a character like newline ('\n').
Im totally new to programming, I picked up a C manual to learn on my own. I dont want to use an array as Im trying to practice with getchar(). I want to be able to output an error message if the user enters anything other than a digit or an alphabet. I am also trying to practice the C library function isalpha() and isdigit(). This is what I wrote so far, but my output is not quite right.
Input 1: "hello"
Expected output : "valid output"
Input 2: "hello5"
Expected output : "valid output"
Input 3: "hello!"
Expected output : "invalid output"
But my program returns "valid input" for all the three inputs above
Please help a newbie try to learn. I greatly appreciate it.
#include <stdio.h>
#include <ctype.h>
int main ()
{
char ch;
int len;
int valid;
printf("Enter a word: ");
for(length = 0; (ch = getchar()) != '\n'; len++)
{
if(isalpha(ch) || isdigit(ch))
{
valid = 1;
}
else
{
valid = 0;
}
}
printf("Input length: %d\n", len);
if (valid == 1)
{
printf("Valid\n");
}
if(valid == 0)
{
printf("\n");
}
return 0;
}
You were almost there. Few pitfalls:
1st there is a typo for your variable name “length” instead of “len”.
2nd As Mitchel0022 stated, your program will always display “valid” providing the last character entered is valid because you reassign a new value for the variable ‘valid’ on each iteration. but you don’t have to use a ‘break statement since you need the loop to continue in order to get your length, so stick with your flag.
Now your program should run fine. Copy and paste the code below:
#include <stdio.h>
#include <ctype.h>
int main ()
{
char ch;
int len;
//flag is set true
int valid = 1;
printf("Enter a word: \n");
for(len = 0; (ch = getchar()) != '\n'; len++)
{
//change flag if character is not number nor letter
if(!isalpha(ch) && !isdigit(ch))
{
valid = 0;
}
}
printf("Input length: %d\n", len);
if (valid == 1)
{
printf("Valid\n");
}
else
{
printf("Invalid\n");
}
return 0;
}
The error here is when checking every character, by toggling valid to 0 and 1 really you are only looking at the last character. What you want to do is for every character as soon as you find one character that is not a digit/alpha character then exit
you can replace your if/else with something like this
vlaid = 1; //always assume its valid
for(int length = 0; (ch = getchar()) != '\n'; length++)
{
if(!isalnum(ch)) //if not a valid character
{
valid = 0; // string is not valid anymore
break; // we can exit the loop
}
}
I am a beginner to C programming and am trying to "Split a string into separate words and write the string in reverse".
Sample Input : Hello World it's FUBAR
Sample Output: FUBAR it's World Hello
I have tried it with this code so far on CodeBlocks 13.12(Windows 8.1/AMD A8) :
#include<stdio.h>
#include<string.h>
char str[100];
char word[100][100];
int main(){
fgets(str,100,stdin);
int i=0,j=0,k=0;
for(i=0;i<100;i++){
while(str[i]!=' ' || str[i]!='\0')
{
word[j][k]=str[i];
i++;
j++;
}
if(str[i]==' '){
k++;
}
}
while(k>0){
for(j=0;j<100;j++){
printf("%s",word[j]);
}
printf(" ");
k--;
}
return 0;
}
The code compiles with 0 errors, 0 warnings.
But when I build and run the code, it crashes with error message -1073741510.
I have been trying for many hours now but have not been able to figure out where exactly the code is breaking.Please help me with this one.
Please try this code.
1) Eliminated extra looping.
2) Swapped j and k variables . Each row would constitute a new word.
3) word[0][1..100] would the first word and word[1][1..100] would be second word.
int main(){
fgets(str,100,stdin);
printf("str is [%s]\n",str);
int i=0,j=0,k=0;
for(i=0;i<100;i++){
printf("char is [%c]\n",str[i]);
if( str[i]!=' ' && str[i]!='\0' )
{
word[j][k]=str[i];
k++;
}else if(isspace(str[i]) || str[i] == ' '){
printf("space found\n");
j++;
}
}
printf("value of j [%d]\n",j);
while(j>=0){
for(k=0;k<100;k++){
printf("%c",word[j][k]);
}
printf(" ");
j--;
}
return 0;
}
Your for loop looks wrong, it should be
for(i=0;i<100;i++)
{
while(str[i]!=' ' || str[i]!='\0')
{
word[j][k]=str[i];
i++;
k++;
}
if(str[i]==' ')
{
j++;
}
}
Notice the k and j increment swap.
In the first while increase k instead of j.
In if(str[i]==' ') set the null termination for word[j][k] and then increase j instead of k.
Below is a Corrected Code. Note the Output doesn't come exactly in one single line. For example the output will always come like this,
EDIT: Thanks to a point reminded by Rad Lexus in the comments. I was able to mitigate the problem a bit
Changes made in Code:
Changed the following code line to
for(i=0;i<strlen(str);i++)
This,
for(i=0;i<strlen(str)-1;i++)
Although, the problem of outputting all the words in the same line is solved,
but there is another problem. Now there is no space between the first and the Second word.
So, the new problem is,
Example 1:
Input: Welcome to Bravo
Output: Bravoto Welcome
Example 2:
Input: Hello World it's FUBAR
Output: FUBARit's World Hello
A temporary solution to the above problem is to change this code
for(m=j;m>=0;m--){
printf("%s",word[m]);
}
To this code,
for(m=j;m>=0;m--){
if(m == j){
printf("%s ",word[m]);
}
else{
printf("%s",word[m]);
}
}
(I guess this problem occurs due to mapping from a 1D Array to a 2D Array and there is probably some padding involved.) -> Edit:This is not due to padding but, "I guess this problem occurs due to.." – no, it occurs due to fgets which also stores the terminating newline code-Rad Lexus.
Anyways, here is the code,
#include<stdio.h>
#include<string.h>
char str[100];
char word[100][100];
int main(){
int i=0,j=0,k=0;
int m=0;
fgets(str,100,stdin);
for(i=0;i<strlen(str)-1;i++){
if(str[i]!=' '){
word[j][k]=str[i];
//printf("%c",word[j][k]);
k++;
}
if(str[i] == ' ' || str[i] == '\0'){
word[j][k]=' ';
k=0;
j++;
}
}
for(m=j;m>=0;m--){
printf("%s",word[m]);/*----->TEMPORARY SOLUTION
for(m=j;m>=0;m--){
if(m == j){
printf("%s ",word[m]);
}
else{
printf("%s",word[m]);
}
}*/
}
return 0;
}
I am writing a C program in which the user has to guess the name of a randomly generated film from a file of 50 film titles. I need to print out the random film title in asterisks but am struggling to do so. For example if the film is "Django Unchained", then "****** *********" will be displayed.
I have two arrays of 50 characters: Film[50] which holds the title of the randomly generated film and Mask[50] which I intened to hold the masked title of the film. Here is the function I have written to mask the title, yet nothing is printed when I print Mask[50].
Any help would be much appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
char FilmArray[50][100];
char Film[50], Mask[50];
int r, i=0;
bool PlayAgain();
void GenerateFilm();
void MaskFilm();
int main()
{
char array[50];
bool answer;
FILE *films;
films = fopen("filmtitles.txt", "r");
if(films == NULL){
printf("\n ************* ERROR *************\n");
printf("\n \"filmtitles.txt\" cannot be opened.\n");
printf("\n PROGRAM TERMINATED\n");
exit(EXIT_FAILURE);
}
while(fgets(array, sizeof array, films) != NULL){
strcpy(&FilmArray[i], array);
i++;
}
printf("\n ************ WELCOME TO MY FILM GENIE GAME ************\n\n");
do{
printf(" Hit ENTER to generate a random film!\n");
getch();
GenerateFilm();
printf("\n %s\n", &Film[50]);
MaskFilm();
printf("\n %s\n", &Mask[50]);
.........
.........
return 0;
}
void GenerateFilm(){
srand(time(NULL));
r = rand() % 49;
strcpy(&Film[50], &FilmArray[r][0]);
}
void MaskFilm(){
for(i=0; i<50; i++){
if((Film[i] >= 'a' && Film[i] <= 'z') || (Film[i] >= 'A' && Film[i] <= 'Z') || (Film[i] >= '0' && Film[i] <= '9')){
Mask[i] = '*';
}
else if(Film[i] == '.'){
Mask[i] = '.';
}
else{
Mask[i] = ' ';
}
}
}
EDIT: Added more of my code
You made a typo Film[i] >= 'A' && Film[i <= 'Z']. Plus you return a char array but your function definition is char MaskFilm(). Apart from these two mistakes your logic is correct. The first mistake is apparent and you can correct it as you have written it correctly for other or condition. As far as second mistake is concerned, you have not passed anything to the function thus I assume your Mask[] array is global so in that case make return type void , don't return anything. Select a film name in global array Film[] ( as you have done most likely ) in main, call your function and after returning to main print your masked array.
EDIT
#KOB I have shared a working version of your code , mainly the mistake was
how you use strcpy. Apart from that there are small changes I have mentioned
in comments of code. Have a look here Updated Code. Also I am also
not that familiar with the rules but if you post a code at least make sure
it runs I had to remove somethings and add before it compiled. Do post in comments if you have doubt regarding the code.
I'm trying to write a program which given a certain number of input will output the product of the listed input (only accounting inputs of 0-9 and ignoring other).
For example:
input:345 would result output: 60, or another example would be, input: 3t4 and output: 12
I have given it many attempts and this is what I'm stuck with :
#include <stdio.h>
main(){
int c,i;
c = getchar();
i = 1;
while (c!= '\n'){
if (c>=48 && c<=57){
i=c*i;
c=getchar();
}
}
printf("%d",i);
}
How can i do this ?
Couple of issues in your code.
After each time the program encounters a non-numeric character it doesn't read further from the input. It reads the same character. Hence c=getchar() should be outside the if block
The multiplication happens for the char variable c. It should be converted to the actual number and then be multiplied. In your code you are multiplying its ascii value. Hence (c-48)*i instead of c*i
Use i=(c-48)*i; instead of i = c*i. So, the changed program would be:
#include <stdio.h>
main(){
int c,i;
c = getchar();
i = 1;
while (c!= '$'){
// printf("%c\n", c);
if (c>=48 && c<=57){
i=(c-48)*i;
}
c=getchar();
}
printf("%d",i);
}
This will ensure that you are using the numeric value of the digit, 0 not as ascii code of 0 but as simple 0.
use c=getchar() outside the if block. This should work.
int i,c;
i = 1;
while (i){
c=getchar();
if(c == '\n')
{
break;
}
if (c < 48 || c > 57)
{
i = -1;
break;
}
i = i * (c-48);
}
if (i == -1)
{
printf("Error. Non-Number Entered\n\n");
}
else {
printf("%d\n\n",i);
}