How to run through a loop multiple times in C? - c

Ok i modified my code but cannot get it to break when the user inputs 0. I tried 0, '0', and "0" and neither break the loop.
#include <stdio.h>
#include<conio.h>
int main(){
int word;
int countword = 0;
int countpunct = 0;
do{
printf("\nEnter the String: ");
while ((word = getchar()) != EOF && word != '\n'){
if (word == ' ' || word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
countword++;
}
if (word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
countpunct++;
}
}
printf("\nThe number of words is %d.", countword);
printf("\nThe number of punctuation marks is %d.", countpunct);
} while (word!= 0);
}

Your inner loops break when word is either EOF or \n. Since you never modify it when you get to the end of the outer loop, the condition will always be true.
Going back to your pre-edit code, all you really need is to change scanf("%c", word); to scanf("%c", &word);, although you should use a separate char variable for that, since the %c format specifier expected a pointer to char. So your code should look like this:
#include <stdio.h>
#include <stdlib.h>
int main(){
int word;
char cont;
for (;;){
int countword = 0;
int countpunct = 0;
printf("\nEnter the String: ");
while ((word = getchar()) != EOF && word != '\n'){
if (word == ' ' || word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
countword++;
}
if (word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
countpunct++;
}
}
printf("\nThe number of words is %d.", countword);
printf("\nThe number of punctuation marks is %d.", countpunct);
printf("\nContinue? Y/N?");
scanf("%c", &cont);
if (cont!= 'y' && cont!= 'Y'){
return 0;
}
}
}
Note also that countword and countpunct are moved inside of the outer loop. That way, they're initialized to 0 for each new set of words.

Related

check multi input char in c

scanf("%c%c%c%c", &var1, &var2, &var3, &var4);
if ((var1 != 'f' || '+' || '-' || '[' || ']') ||
(var2 != 'f' || '+' || '-' || '[' || ']') ||
(var3 != 'f' || '+' || '-' || '[' || ']') ||
(var4 != 'f' || '+' || '-' || '[' || ']'))
printf("Invaild input\n");
this is my code,i want user to enter 4 variables with space between each one and the output to be invaild if the input is diffrent from any of this chars.right now no matter what i enter into the code the "invalid input" is the output. is there something wrong in here?
The main reason why it does not work is because your conditions like (var1 != 'f' || '+' || '-' || '[' || ']') do something completely different than you might think. An expression like (anyBooleanValue || '+') will always return true, regardless what the value of anyBooleanValue is. This is because the RHS operand '+' is a character literal, i.e. an integral value representing (very likely) the ASCII-code of character '+'. Any integral value other than 0 is treated as true, so it reads like anyBooleanValue || true, which obviously is always true.
So you actually would have to write something like if (var1 != 'f' && var1 != '+' && ... as #WhozCraig mentioned.
But actually you have the same code appearing again and again, and such cases are usually handled by loops. And the test of whether a character appears in a set of possible characters can be solved easily with function strchr, which returns a pointer to the first occurrence of the character in question or NULL, if the character does not occur. The following code illustrates this:
int main() {
#define nvars 4
char vars[nvars];
int i;
for (i=0; i<4; i++) {
scanf(" %c", &vars[i]);
if (strchr("f+-[]",vars[i]) == NULL) { // char not found?
break;
}
}
if (i<4) {
printf("Invaild input\n");
} else {
printf("valid.\n");
}
}
Note further the leading blank in scanf(" %c", which is for consuming white spaces before the actual character.
#Stephan Lechner well identified the problems with OP's code and a good solution. Below is an alternative solution to check if a character is one of several characters in one step. Use a look-up table.
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
int mango_test(unsigned char ch) {
// If char is not too big
#if UCHAR_MAX < 1024
static const bool good[UCHAR_MAX + 1] = { //
['f'] = 1, ['+'] = 1, ['-'] = 1, ['['] = 1, [']'] = 1}; // look-up table
return good[ch];
#else
char *s = strchr("f+-[]", ch);
return s && ch; // Found in list and not the null character.
#endif
}
int main(void) {
for (int ch = SCHAR_MIN; ch <= UCHAR_MAX; ch++) {
int found = mango_test(ch);
if (found)
printf("Found %d <%c>\n", ch, ch);
}
}
Output
Found 43 <+>
Found 45 <->
Found 91 <[>
Found 93 <]>
Found 102 <f>

do while loop that doesn't end in C

In this program I am attempting to save each character that the user inputs into a do while loop that should count the number of spaces, new lines, and tabs.
When I run my program it doesn't end when '.', '!', or '?'
Why?
int characters, spaces, new_lines, tabs;
int user_input;
printf("Enter a sentence (end by '.' or '?' or '!'):");
do{
user_input = getchar();
if (user_input == ' ')
spaces++;
if (user_input == '\t')
tabs++;
if (user_input == '\n')
new_lines++;
} while((user_input != '.') || (user_input != '?') || (user_input != '!'));
printf("Number of space characters: %d", spaces);
printf("Number of new line characters: %d", new_lines);
printf("Number of tabs: %d", tabs);
return 0;
(user_input != '.') || (user_input != '?') || (user_input != '!')
The above doesn't evaluate the way you think it does. For the condition to be false (and the loop to stop) all three clauses must be false. That means that all respective inverses must be true, i.e:
(user_input == '.') && (user_input == '?') && (user_input == '!')
And that is of course impossible. A single character variable cannot contain three different values at once.
I assume you want the loop to terminate if the program receives either of those characters as input, so you need to check that the input is neither of those, meaning:
(user_input != '.') && (user_input != '?') && (user_input != '!')

C How to Capitalize character after punctuation mark without Arrays?

I am very new to the C programming language and was curious how would you capitalize a letter in a program following a punctuation mark without using an array. I tried using the ASCII code values by subtracting 32 but it just doesn't seem to work in my code. Here is a portion of my code that outputs the letters. I thought word = word - 32 would work but it does nothing when running the program. I'd appreciate the help!
while ((word = getchar()) != EOF && word != '\n'){
if (word == ' ' || word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&' || word == ';' || word == ':'){
printf("\n");
word = word - 32;
}
if ((word >= 'A' && word <= 'z')){
printf("%c", word);
}
}
You can use a flag to check whether the last entry was a punctuation, and then alter the next input based on the flag and reset it again
char word;int flag=0;
while ((word = getchar()) != EOF && word != '\n'){
if(flag==1){
printf("\n");
word = word - 32; flag=0;
}
if (word == ' ' || word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&' || word == ';' || word == ':'){
flag=1;
}
if ((word >= 'A' && word <= 'z')){
printf("%c", word);
}
}

Programming in C how to output inputted string onto the screen?

I am trying to to have my program output the words inputted into my program onto the screen. So far, my program outputs random characters depending on what I type. For example, if I input the word hey, it outputs on the screen %. How do I go about fixing this to output the word hey on the screen? My code is down below.
#include <stdio.h>
#include<conio.h>
int main(){
int word;
char cont;
for (;;){
int countword = 0;
int countpunct = 0;
printf("\nEnter the String: ");
while ((word = getchar()) != EOF && word != '\n'){
if (word == ' ' || word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
countword++;
}
if (word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
countpunct++;
}
}
printf("%c", word);
printf("\nThe number of words is %d.", countword);
printf("\nThe number of punctuation marks is %d.", countpunct);
printf("\nContinue? Y/N?");
scanf("%c", &cont);
if (cont != 'y' && cont != 'Y'){
return 0;
}
}
}
You are using & with printf(). It will print the address of the variable (and not its value)!
Do this instead:
printf("%c", word); // notice there is no &
Apart from that, I noticed a few things in your code worth mentioning:
word is declared as an int, but is read and printed as a char. Why?
Your while loop makes it sure that word holds either EOF or \n while it exits the while loop.
while ((word = getchar()) != EOF && word != '\n')

Is there something wrong with my gets function? we haven't been though about fgets yet in class. only gets

for example when I type in a string "Hello", when I press 'a' it should print "There are 2 vowels." Instead, it says there are 0. I'm new to programming and this is the first language I am learning. Help?
/*
Student: Josiah Eleazar T. Regencia
Course: BSIT 1
Subject: SCS 101
Professor: Daniel B. Garcia
Problem definition:
Write a menu program that will count the vowels and consonants in the string
*/
#include <stdio.h> //printf and scanf functions
#include <string.h> //string functions
#include <stdlib.h>
#include <conio.h>
#define PROMPT "Type in a word, a phrase, or a sentence." //instucts the user
/*
Declaring the function for the user's menu
*/
void menu();
/*
Declaration of function needed to count the vowels in the string
*/
int vowel_count(char *stringInput); //declaring the function to count the vowels sounds
/*
Declaration of function needed to count the consonants in the stringn
*/
int consonant_count(char *stringInput); //declaring the functions to count the consonant sounds
/*
Declaring the function needed to convert the streeting to uppercase
*/
int uppercase(char *stringInput);
/*
Declaring the function needed to convert the streeting to uppercase
*/
int lowercase(char *stringInput);
int main () {
char userInput[100]; // the string the user inputs
char commandKey[1]; //this key is for the menu
char newInput[100]; //this is for the new input to user will put in
int stringLength; //to identify the length of the string
/*
Variables for counting the vowels and consonants
*/
int consonantCount;
printf("%s\n\n", PROMPT); //instucts the user
gets(userInput);
stringLength = strlen(userInput); //gets the length of the string
//fgets(userInput, 100, stdin);
/*if(stringLength > 0 && userInput[stringLength - 1] == '\n') {
userInput[stringLength - 1] ='\0';
}*/
menu(); //prints out the menu for the user to pick his options
/*
The loop will run what the user asks the program to run while at the same time also asking
what the programmer wants next
*/
while(*commandKey != 'X' || *commandKey != 'x') {
//int commandLength; //length of the command key
printf("Enter your menu selection: ");
gets(commandKey);
/*commandLength = strlen(commandKey);
fgets(commandKey, 100, stdin);
if(commandLength > 0 && commandKey[commandLength - 1] == '\n') {
commandKey[commandLength - 1] ='\0';
}*/
if(*commandKey == 'A' || *commandKey == 'a') {
int vowelCount;
vowelCount = vowel_count(userInput);
printf("There are %d vowels.\n\n", vowelCount);
}
if(*commandKey == 'B' || *commandKey == 'b') {
consonantCount = consonant_count(userInput);
printf("There are %d consonants.\n\n", consonantCount);
}
if(*commandKey == 'C' || *commandKey == 'c') {
/*
This condition simply converts the input string to all lowercase letters
*/
lowercase(userInput);
}
if(*commandKey == 'D' || *commandKey == 'd') {
/*
This condition simply converts the input string to all lowercase letters
*/
uppercase(userInput);
}
if(*commandKey == 'E' || *commandKey == 'e') {
/*
Prints the current string
if the string was converted in lowercase letters, the outcome would be all lowercase letters
if the string was converted in uppercase letters, the outcome would be all uppercase letters
*/
printf("%s\n\n", userInput);
}
if(*commandKey == 'F' || *commandKey == 'f') {
/*
When the user wants to test a new string, this is the condition for the user
to automatically ask of it
*/
printf("%s\n", PROMPT);
gets(newInput);
strcpy(userInput, newInput);
}
if(*commandKey == 'M' || *commandKey =='m') {
/*
In case the user forgets, this will serve as a reminder of the menu
*/
menu();
}
if(*commandKey == 'X' || *commandKey == 'x') {
printf("Goodbye!\n");
break;
}
}
}
//Function that displays the menu.
void menu() {
/*
These are the set of command keys given to the user
*/
printf("\n\n\n");
printf("PRESS:\n\n");
printf(" A - Count the number of vowels in the string.\n");
printf(" B - Count the number of consonants in the string.\n");
printf(" C - Convert the string to uppercase.\n");
printf(" D - Convert the string to lowecase.\n");
printf(" E - Display the current string.\n");
printf(" F - Enter another string.\n");
printf("\n");
printf(" M - Display this menu.\n");
printf(" X - Exit the program.\n");
printf("\n\n");
}
/*
Defining the function for the vowel counting
*/
int vowel_count(char *stringInput) {
if ( *stringInput == '\0')
return 0;
else
return vowel_count(stringInput + 1) + (*stringInput == 'a' || *stringInput == 'A')
+ (*stringInput == 'e' || *stringInput == 'E')
+ (*stringInput == 'i' || *stringInput == 'I')
+ (*stringInput == 'o' || *stringInput == 'O')
+ (*stringInput == 'u' || *stringInput == 'U');
}
/*
Defining the function for the vowel counting
*/
int consonant_count(char *stringInput) {
if (*stringInput == '\0')
return 0;
else
return consonant_count(stringInput + 1) + (*stringInput == 'b' || *stringInput == 'B')
+ (*stringInput == 'c' || *stringInput == 'C')
+ (*stringInput == 'd' || *stringInput == 'D')
+ (*stringInput == 'f' || *stringInput == 'F')
+ (*stringInput == 'g' || *stringInput == 'G')
+ (*stringInput == 'h' || *stringInput == 'H')
+ (*stringInput == 'j' || *stringInput == 'J')
+ (*stringInput == 'k' || *stringInput == 'K')
+ (*stringInput == 'l' || *stringInput == 'L')
+ (*stringInput == 'm' || *stringInput == 'M')
+ (*stringInput == 'n' || *stringInput == 'N')
+ (*stringInput == 'p' || *stringInput == 'P')
+ (*stringInput == 'q' || *stringInput == 'Q')
+ (*stringInput == 'r' || *stringInput == 'R')
+ (*stringInput == 's' || *stringInput == 'S')
+ (*stringInput == 't' || *stringInput == 'T')
+ (*stringInput == 'v' || *stringInput == 'V')
+ (*stringInput == 'w' || *stringInput == 'W')
+ (*stringInput == 'x' || *stringInput == 'X')
+ (*stringInput == 'y' || *stringInput == 'Y')
+ (*stringInput == 'z' || *stringInput == 'Z');
}
/*
Defining the function for the conversion of the string to all uppercase letters
*/
int uppercase(char *stringInput) {
while(*stringInput) {
*stringInput = toupper(*stringInput);
stringInput++;
}
}
/*
Defining the function for the conversion of the string to all uppercase letters
*/
int lowercase(char *stringInput) {
while(*stringInput) {
*stringInput = tolower(*stringInput);
stringInput++;
}
}
This loop will never stop:
while(*commandKey != 'X' || *commandKey != 'x')
A loop stops when its condition is false. For *commandKey != 'X' || *commandKey != 'x' to be false, it is logically equivalent for *commandKey == 'X' && *commandKey == 'x' to be true, which doesn't quite work. *commandKey can't be both 'X' and 'x'.
Instead, you want:
while(*commandKey != 'X' && *commandKey != 'x')
Which will stop when *commandKey is 'X' or 'x'.
Also, you never initialized commandKey, so you can't test it in the loop (using values of uninitialized variables is undefined behavior). And if you want to treat it as a string, you need to declare it such that it holds at least 2 characters, because the null character is needed:
char commandKey[2] = { 0 };
This will initialize commandKey to an empty string. Remember that gets() will null-terminate the string, so, even if your command is just one key, gets() will need at least 2 positions to fill - the character command and the null terminating byte. Alternatively, you can leave commandKey as is (provided that you initialize it), and use getchar() instead, which reads one single character.

Resources