Second printf is not coming up and I am unsure why - c

This is my code. The second printf and getchar does not pop up after hitting enter for the first scanf. I am unsure why the second printf and getchar are not working and what the fix would be.
#include <stdio.h>
int main()
{
int choice;
int i;
i = 0;
int n;
n = 1;
int p;
char message[1000];
printf("Would you like to (1) encrypt or (2) decrypt?: ");
scanf("%i\n", choice);
printf("\nType your message: ");
message[p] = getchar();
for (i = 1; (i < 1000 && message[p] != '\0');) {
message[p] = message[p] + n;
n + 1;
}
for (i = 0; (i < 1000 && message[p] != '\0');) {
message[p] = message[p] - n;
n + 1;
}
return 0;
}

Your encription method works for encription and decription. This compiles and takes in a string including spaces modifies it and prints it out.
#include <stdio.h>
int main() {
int choice;
char temp;
int i = 0;
int n = 1;
int p, b;
char message[1000];
char endmessage[1000];
printf("Would you like to (1) encrypt or (2) decrypt?: ");
scanf("%i", &choice); // change as per comment above
scanf("%c", &temp); /* temp statement to clear buffer otherwise a second character has to be typed before the next print statement is executed */
printf("Type your message: "); //prompt added for user clarity
scanf("%[^\n]", message); /* this scanf line allows for spaces in the message */
printf("\nmessage typed is: %s \n", message);
p = (sizeof( message) + 1); /* strings need to have an ending '\0'
message[p] = '\0';
if (choice == 1) {
for (i = 0; (i < 1000 && message[i] != '\0');) {
endmessage[i] = (message[i] + n);
i +=1;
}
b = (sizeof( endmessage)); // replace encripted \0 with '\0'
endmessage[b] = putchar('\0');
printf("\nYour message encripted is: %s\n\n", endmessage);
}
if (choice == 2) {
for (i = 0; (i < 1000 && message[i] != '\0');) {
endmessage[i] = message[i] - n;
i += 1;
}
b = (sizeof(endmessage) -2); // replace decripted \0 with '\0'
endmessage[b] = putchar('\0');
printf("\nYour message decripted is: %s\n\n", endmessage);
}
}

Related

Searching an Array of Strings from User Input in C

I've got this homework assignment where we get the user to enter the amount of lines of strings they desire, they then proceed to enter them which gets stored in a 2D Array (thus creating an array of strings). Then a switch case menu will be displayed which should
Search a character entered by the user, returns the amount of times the character occurred in the array
Search a word entered by the user, returns the amount of times the word occurred in the array
Have the user enter a specified word length and return the amount of times words of the specified length occur.
I have a couple problems with my code. The program runs without errors from the compiler. The searchByCharacter function works fine but the searchByWord only returns a value of 0 regardless of any word inputted and nothing happens after I input a number for the searchByLength function. The program freezes after I enter a length once I select the searchByLength function. I've been at this for a while and I don't know where I'm going wrong.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE_LENGTH 80
#define MAX_LINES 10
#define WORD_LENGTH 20
void readText(char text[][MAX_LINE_LENGTH], int n)
{
int i;
printf("Enter %d number of lines:\n", n);
for(i = 0; i < n; i++)
{
scanf(" %[^\n]s", text[i]);
}
}
int searchByCharacter(char text[][MAX_LINE_LENGTH], int n, char c)
{
int i, charCount = 0, j = 0;
for(i = 0; i < n; i++)
{
j = 0;
while(text[i][j] != '\0')
{
if(text[i][j] == c)
{
charCount++;
}
j++;
}
}
return charCount;
}
int searchByWord(char text[][MAX_LINE_LENGTH], int n, char * keyword)
{
int i, wordCount = 0;
for(i = 0; i < n; i++)
{
int j = 0;
int lengthOfWord = 0;
char wordCheck[WORD_LENGTH];
char * currentLine = text[i];
while(currentLine[j] != '\0')
{
if (currentLine[j] == ' ' || currentLine[j] == '\n' || currentLine[j] == ',' || currentLine[j] == '.' ||
currentLine[j] == ';')
{
wordCheck[lengthOfWord] = '\0';
int matchingWord = strcmp(wordCheck, keyword);
if(matchingWord == 0)
{
wordCount++;
}
lengthOfWord = 0;
j++;
continue;
}
wordCheck[lengthOfWord] = currentLine[n];
lengthOfWord++;
j++;
}
}
return wordCount;
}
int searchByLength(char text[][MAX_LINE_LENGTH], int n, int wordLen)
{
int i, lengthCount = 0;
for(i = 0; i < n; i++)
{
int lengthOfWord = 0;
int j = 0;
char * currentLine2 = text[i];
while(currentLine2[j] != '\0')
{
if (currentLine2[j] == ' ' || currentLine2[j] == '\n' || currentLine2[j] == ',' || currentLine2[j] == '.' ||
currentLine2[j] == ';')
{
if(lengthOfWord == wordLen)
{
lengthCount++;
}
lengthOfWord = 0;
n++;
continue;
}
lengthOfWord++;
n++;
}
}
return lengthCount;
}
int main(void)
{
char textInput[MAX_LINES][MAX_LINE_LENGTH];
printf("Enter number of lines (<10): ");
int textLines = 0;
scanf("%d", &textLines);
while(textLines < 1 || textLines > 10)
{
printf("Invalid Input.\n");
printf("Enter number of lines (<10): ");
scanf("%d", &textLines);
}
if(textLines >= 1 && textLines <= 10)
{
readText(textInput, textLines);
int menuActive = 1;
while(menuActive)
{
printf("\nText Analysis\n----\n");
printf("1-Search By Character\n2-Search By Word\n3-Search By Length\n0-Quit\nPlease enter a selection: ");
int selection;
scanf("%d", &selection);
switch(selection)
{
case 0:
menuActive = 0;
break;
case 1:
printf("Selected 1\n");
printf("Enter a character to search: ");
char characterSearch;
scanf(" %c", &characterSearch);
int characterwordCount = searchByCharacter(textInput, textLines, characterSearch);
printf("\nNumber of occurence of %c = %d", characterSearch, characterwordCount);
break;
case 2:
printf("Selected 2\n");
printf("Enter a word to search: ");
char wordSearch[MAX_LINE_LENGTH];
scanf(" %s", wordSearch);
int lengthwordCount = searchByWord(textInput, textLines, wordSearch);
printf("\nNumber of occurence of %s = %d", wordSearch, lengthwordCount);
break;
case 3:
printf("Selected 3\n");
printf("Enter search length: ");
int wordLength;
scanf(" %d", &wordLength);
int wordLengthwordCount = searchByLength(textInput, textLines, wordLength);
printf("Number of words with length %d = %d", wordLength, wordLengthwordCount);
break;
default:
printf("Invalid Input.\n");
}
}
printf("You Have Quit!\n");
}
return 0;
}

Keep characters in an array

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].

I am getting a _\377 in my output

I have a school assignment to make a hangman game. The game works how I want it to except for one small glitch. If the user entered word is 4 letters or less, the hidden word is displayed with an extra "_\377" at the end. When the user entered word is 5 letters or more, then there is no glitch. I am hoping that someone would be kind enough to help me trouble shoot the problem. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int letterfinder(char string[], char a, int vari)
{
int length = strlen(string);
int i = vari;
int val = 0;
while( i <= length && val != 1)
{
if( string[i] == a)
{
val = 1;
}
i++;
}
if( val == 0)
{
return 100;
}
else
{
return i;
}
}
int main()
{
char inWord[] = "1111111111111111111111111111";
char outWord2[] = "1111111111111111111111111111";
char guess;
int gameover = 0;
int trys = 10;
int vari = 0;
printf("Please enter a word: ");
gets(inWord);
printf("%s\n", inWord);
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
printf(" \n");
int i2 = 0;
int j2 = 0;
int i3 = 0;
i2 = strcspn(inWord, outWord2);
char outWord[80];
while(i3 < i2)
{
outWord[i3] = '1';
i3++;
}
while(j2 < i2)
{
outWord[j2] = '-';
j2++;
}
puts(outWord);
while(gameover != 1 )
{
printf("What is your guess: ");
scanf("%s", &guess);
vari = 0;
if(letterfinder(inWord, guess, vari) == 100)
{
printf("Wrong!");
trys--;
printf("You have %d attempts left\n", trys);
if(trys == 0)
{
gameover = 1;
printf("You ran out of attempts. Game over\n");
}
}
else
{
outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
vari = (letterfinder(inWord, guess, vari));
while(letterfinder(inWord, guess, vari) != 100)
{
outWord[(letterfinder(inWord, guess, vari) - 1)] = guess;
vari = letterfinder(inWord, guess, vari);
}
puts(outWord);
}
int value = 0;
i3 = 0;
while( i3 <= i2)
{
if( outWord[i3] == '-')
{
value = 1;
}
i3++;
}
if(value != 1)
{
printf("Congratulations, you have guessed the word!\n");
gameover = 1;
}
}
return 0;
}
Your code has Undefined Behaviour. In the cases it "works" it is only by chance/luck. char guess; scanf("%s", &guess); That causes memory corruption as you are writing a string to a variable that can only hold a single char. Even a single letter guess will require two characters to store as all C strings are NUL terminated.
– kaylum

I can't read the second string, no matter how many getchar i insert

This program need to read two strings, this two strings will be passed to the "confirm" function, they will be read and the the function will have to find a word in common.
But in the main i cant read the "string2" string! No matter how many getchar i insert.
#include <stdio.h>
#include <string.h>
void confirm(char string1[],char string2[]){
char word[20];
char w_aux[20];
int i, j, k, l, m;
int len1, len2;
int find;
i = 0;
len1 = strlen(string1);
len2 = strlen(string2);
while (i < len1){
j = 0;
while ((string1[i] != ' ') && (i < len1)){
word[j] = string1[i];
i++;
j++;
}
word[j] = '\0';
k = 0;
find = 0;
while((k < len2) && (find == 0)){
l = 0;
while ((string2[k] != ' ') && (k < len2)){
w_aux[l] = string2[k];
k++;
l++;
}
w_aux[l] = '\0';
if (j == l){
m = 0;
while((word[m] == w_aux[m]) && (m<j)){
m++;
}
if (m == j){
find = 1;
}
}
k++;
}
i++;
}
printf("%s\n", word);
}
int main (){
char string1[20];
char string2[20];
printf("Type the first text: \n");
scanf("%[^\n]s", string1);
printf("Type the second text: \n");
scanf("%[^\n]s", string2);
getchar();
confirm(string1, string2);
return 0;
}
Use getchar after input of string 1 for \n:
printf("Type the first text: \n");
scanf("%[^\n]", string1);
getchar(); //here
printf("Type the second text: \n");
scanf("%[^\n]", string2);
Just change the format specifier to "%19[^\n]*c", it will take the trailing '\n' character away.

Program errors due to strcmp and strcpy in C

No matter how I edit my program there seems to be overflow errors and mismatching type errors. Can someone help me to make this run without errors.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int choice;
int i;
int j;
char type;
int amount;
int don_count = 0;
int req_count = 0;
int flag;
char donations_inv_type[100][20];
int donations_amount[100];
char requests_inv_type[100][20];
int req_amount[100];
printf("Welcome to the Food Bank Program\n\n 1. Add a donation\n 2. Add a request\n 3. Fulfill a request\n 4. Print status report\n 5. Exit\n\nEnter your choice: ");
scanf("%d", &choice);
while (choice != 5) {
if (choice == 1) {
printf("\nEnter inventory type: ");
scanf("%s", &type);
printf("Enter the amount: ");
scanf("%d", &amount);
printf("\nDonation Added!\n\n");
flag = -99;
for (i = 0; i < don_count; i++) {
if (strcmp(donations_inv_type[i], type) == 0)
flag = i;
}
if (flag == -99) {
strcpy(donations_inv_type[i], type);
donations_amount[i] = amount;
don_count++;
}
else
donations_amount[flag] += amount;
printf("Donation Added!\n");
printf("Press any key to continue . . .\n\n");
}
else if (choice == 2) {
printf("\nEnter inventory type: ");
scanf("%s", &type);
printf("Enter the amount: ");
scanf("%d", &amount);
strcpy(requests_inv_type[req_count], type);
req_amount[req_count] = amount;
req_count++;
}
else if (choice == 3) {
printf("\n\n-------- Fulfilling Requests--------");
flag = -99;
for (i = 0; i < don_count; i++) {
if (strcmp(donations_inv_type[i], requests_inv_type[0]) == 0)
flag = i;
}
if (flag == -99)
printf("Cannot be Fulfilled\n\n");
else if (donations_amount[flag] > req_amount[0]) {
donations_amount[flag] -= req_amount[0];
printf("Request Fulfilled");
req_amount[0] = 0;
}
else if (donations_amount[flag] == req_amount[0]) {
printf("Request Fulfilled");
for (i = flag; i < don_count; i++) {
strcpy(donations_inv_type[i], donations_inv_type[i + 1]);
strcpy(donations_amount[i], donations_amount[i + 1]);
}
don_count--;
for (i = flag; i < req_count; i++) {
strcpy(requests_inv_type[i], requests_inv_type[i + 1]);
strcpy(req_amount[i], req_amount[i + 1]);
}
req_count--;
}
else if (donations_amount[flag] < req_amount[0]) {
printf("Partially Fulfilled");
req_amount[0] -= donations_amount[flag];
for (i = flag; i < don_count; i++) {
strcpy(donations_inv_type[i], donations_inv_type[i + 1]);
strcpy(donations_amount[i], donations_amount[i + 1]);
don_count--;
}
}
}
else if (choice == 4) {
printf("Printing the Donations Table\n\n");
for (i = 0; i < don_count; i++) {
printf("%s %d", donations_inv_type[i], donations_amount[i]);
}
printf("Printing the Requests Table\n\n");
for (i = 0; i < req_count; i++) {
printf("%s %d", requests_inv_type[i], req_amount[i]);
}
}
printf("Welcome to the Food Bank Program\n\n 1. Add a donation\n 2. Add a request\n 3. Fulfill a request\n 4. Print status report\n 5. Exit\n\nEnter your choice: ");
}
}
Any help is greatly appreciated and I would love an explanation as to what I did wrong so that I can learn and not make the same mistakes next time.
Declare type as character array.
char type[50];
Remove & in scanf(). You should not use & while reading string.
scanf("%s", &type); ==> scanf("%s", type);
^
Here you want to copy integers not strings
strcpy(donations_amount[i], donations_amount[i + 1]);
strcpy(req_amount[i], req_amount[i + 1]);
Modify like this
donations_amount[i]=donations_amount[i + 1];
req_amount[i]= req_amount[i + 1];
Instead of char type you need char type[100]
Error in your code:
if (strcmp(donations_inv_type[i], type) == 0)
// ^^^^ should be char*
Note: Functions strcmp() and strcpy() should be passed \0 nul-terminated array of char (or say string).
Your scanf should look like scanf("%s", type);

Resources