while loops , int vs char reading from scanf , true and false - c

#include <stdio.h>
int main()
{
int number; // We make 1 int named number
scanf("%d",&number); // We give to number some number xd
while (number!=0)// We made a loop while if number isn't 0 do that
{
printf("text");// print text
scanf("%d",&number); // and get again a number.
// So everything works well beside inserting some char instead of int.
// So what is the problem wont scanf return 0 so we exit the program not
// just printing a text all day? That's my first question.
}
return 0;
}
The second problem is how to make a program reading numbers from keyboard till I enter some special sign for ex '.' Yea we do it with loop while right? But how when scanf("%d",&something) it give me back 0 if I enter everything but number?

change it from scanf int to char
Assumption: You are reading a single char at a time
#include <stdio.h>
int main()
{
char c = "0";
int n = 0;
while (n != 46)// we made a loop while if char isn't '.' ASCII - 46 do that
{
scanf(" %c", &c);
n = (int)c;
printf("text %d", n);
//Add if statement to confirm it is a number ASCII 48 - 57 and use it.
}
return 0;
}
EDIT:
Just some more info on how to use numbers:
input number one by one or just a whole number like 123 with some ending special char like ';' or change the line
scanf(" %c", &c);
to:
scanf("%c", &c);
this way it will register '\n' as ASCII 10
use that with atoi to get the actual int value and use it.
EDIT 2:
#World, you cannot expect to read only numbers and '.'
One way to do this with your own code is:
#include <stdio.h>
int main()
{
char c = "0";
int n = 0;
int number = 0;
while (n != 46)// we made a loop while if char isn't '.' ASCII - 46 do that
{
scanf("%c", &c);
n = (int)c;
if (n>=48 && n<=57) {
number *= 10;
number += (n-48);
}
if (n==10) {
printf("text %d\n", number);
//Use number for something over here
number = 0;
}
}
return 0;
}
EDIT 3:
Logic behind this:
Let's say you enter 341 in the console
the line
scanf("%c", &c);
will read this one by one thus reading '3', '4', '1' and '\n' respectively
the while loop
while (n != 46)
will thus run 4 times where:
1st time
c = '3';
n = 51;
if (n>=48 && n<=57) is true;
number = 0 * 10;
number = number + n - 48 = 0 + 51 - 48 = 3
2nd time
c = '4';
n = 52;
if (n>=48 && n<=57) is true;
number = 3 * 10 = 30;
number = number + n - 48 = 30 + 52 - 48 = 34
3rd time
c = '1';
n = 49;
if (n>=48 && n<=57) is true;
number = 34 * 10 = 340;
number = number + n - 48 = 340 + 49 - 48 = 341
4th time
c = '\n';
n = 10;
if (n>=48 && n<=57) is false;
if (n==10) is true;
it prints "text 341" and sets number to 0
while loop exits when c = '.' and n = 46

how to make a program reading numbers from keyboard till I enter some special sign for ex '.'
When scanf("%d",&number) returns 0, there is some non-numeric input. Read that non-numeric input with alternate code.
#include <stdio.h>
int main() {
while (1) {
int number;
int scan_count = scanf("%d", &number);
if (scan_count == EOF) break; // End-of-file or rare input error.
if (scan_count != 1) {
int ch = fgetc(stdin);
if (ch == '.') break; // Expected non-numeric input to break the loop.
printf("Unexpected input character '%c'\n", ch);
} else {
printf("Expected numeric input: %d\n", ch);
}
} // endwhile
printf("Done\n");
}
A better approach is to ditch scanf() and use fgets()` to read user input. Then process the inputted string.

Related

C: first number in array becomes 0 for unknown reason

The Program:
This was supposed to be a simple reverse polish notation addition program, please ignore the EOF break thing, it's a placeholder.
Input is c, always one numeral number, it gets transfered to x where every next numeral c will be added to the number x, so for example when we input c as 1,2 and 3 x will be 123.
When we input 'e' it will mark the start of a new number, and x will be transfered to the stack[0] after the entire stack gets pushed back, and x will become 0. When inputing '+' addition happens, the last two numbers will be summed, x and the first number in the stack, or the first and second number in the stack, or the first number in the stack will duplicate itself.
The Problem:
The first number in the stack array will randomly become 0 and I cannot see where I made the error. The first number (stack[0]) only gets the value zero at the start, never again. At times when inputting '+' it will just get a value.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int stack[16];
int x;
int i;
char c;
//int c;
x=0;
for (i = 0; i < 16; i++)
{
stack[i]=0;
}
while(1)
{
//input character
scanf("%s", &c);
if (c == EOF) break;
//put x to stack
else if (c == 'e')
{for (i = 15; i >0; i--)
{
stack[i]=stack[i-1];
}
stack[0] = x;
x = 0;
}
//reverse polish addition
else if (c == '+')
//if x is 0 go immediately to the stack
{if (x == 0)
//if both x and the second number in array are 0 just duplicate the first number
if (stack[1] == 0)
stack[0] = stack[0] + stack[0];
//if only x is 0 add the first number on the second
else
{
stack[0]=stack[0]+stack[1];
//push back the array to fill the gap on the second number
for (i = 1; i <15; i++)
{
stack[i]=stack[i+1];
}
}
else
{
stack[0] = stack[0] + x;
x = 0;
}
}
else
{
x = x * 10 + ((int)c-0x30);
// putchar(c);
}
printf("X=%d\n",x);
//print stack
for (i = 0; i < 16; i++)
{
printf("%d \t",stack[i]);
}
printf("\n");
}
return 0;
}
Problem 1
scanf("%s", &c); causes undefined behavior. Use scanf(" %c", &c);.
Problem 2
c is never going to be equal to EOF by using scanf. Hence, the following line is useless.
if (c == EOF) break;
The following will take care of both problems.
// Use " %c" instead of "%c" to skip leading whitespace characters.
while ( scanf(" %c", &c) == 1 )
{
}

Re-prompting a user until he/she enters a positive integer value greater than 1

I'm solving CS50 (problemset 1) i.e water.c. It asks user to write a program that prompts the user for the length of his or her shower in minutes (as a positive integer) and then prints the equivalent number of bottles of water (as an integer).
1 min of shower = 12 bottles consumed
MAIN PROBLEM: The problem is that we have to ensure that the user inputs a positive number of minutes otherwise it keeps on re-prompting his back to input/scanf statement. As long as he enters he enters length<=0, I can re-prompt him back using while(length<=0) condition but as he enters a character i.e abc123 in input my code keeps on executing. Any solutions??
>
#include <stdio.h>
int main()
{ int length=0;
int min=12;
int bottle=0;
printf("Enter length of his or her shower in minutes");
scanf("%d", &length);
while (length <= 0){
printf("Enter length of his or her shower in minutes");
scanf("%d", &length);
}
bottle= (min*length);
printf("%d", bottle);
return 0;
}
You can solve this by reading a string first, and then extracting any number:
#include <stdio.h>
int main(void)
{
int length = 0;
char input[100];
while(length <= 0) {
printf("Enter length: ");
fflush(stdout);
if(fgets(input, sizeof input, stdin) != NULL) {
if(sscanf(input, "%d", &length) != 1) {
length = 0;
}
}
}
printf("length = %d\n", length);
return 0;
}
Program session:
Enter length: 0
Enter length: -1
Enter length: abd3
Enter length: 4
length = 4
Crucially, I always check the return value from scanf, the number of items successfully converted.
If you don't care about Inputs like 1f then the Above Answers are ok For you, but if you do not want to accept this kind of Input, then the following approach does something like that:
#include<stdio.h>
int checkInput(void);
int main(void){
int number = checkInput();
printf("\nYour number is\t%d\n",number);
return 0;
}
int checkInput(void){
int option,check;
char c;
do{
printf("Please type a number:\t");
if(scanf("%d%c",&option,&c) == 0 || c != '\n'){
while((check = getchar()) != 0 && check != '\n' && check != EOF);
printf("\tI sayed a Number please\n\n");
}else{
if ( option < 1){
printf("Wrong input!\n");
}else{
break;
}
}
}while(1);
return option;
}
Output:
Please type a number: 1f
I sayed a Number please
Please type a number: f1
I sayed a Number please
Please type a number: -1
Wrong input!
Please type a number: 1
Your number is 1
You don't need the first prompt outside the loop because you have already initialised length to zero, so the loop will prompt at least once.
On most platforms other then Wndows, you need to flush stdout to show text not terminated with a newline.
scanf will return so long as a newline character is buffered and %d alone will not consume the newline, so you need to ensure that any remaining characters up to and including the newline are flushed to prevent an endless loop.
It is good practice to check the return value from scanf() since it makes no guaranteed about not modifying its arguments even when a conversion fails.
It is not clear why min is a variable here sine it is initialised but never re-assigned, but presumably that may be the case in the final program?
#include <stdio.h>
int main( void )
{
int length = 0 ;
int min = 12 ;
int bottle = 0 ;
while( length <= 0 )
{
int converted = 0 ;
printf( "Enter length of his or her shower in minutes: " ) ;
fflush( stdout ) ;
converted = scanf( "%d", &length ) ;
if( converted != 1 )
{
length = 0 ;
}
while( (c = getchar()) != '\n' && c != EOF ) { } // flush line buffer
}
bottle = min * length ;
printf( "%d", bottle ) ;
return 0;
}
int min = 0;
do {
printf("Enter minutes: ");
scanf("%i", &min);
} while(min <= 0);
//programs resumes after this.

How to count the number of words that contain at least 3 vowels

I was wondering if I could ask for some help. I am writing a program in C that writes out the number of characters, words, and vowels are in the string(with a few added print statements). I am trying to figure out how to write a code that loops through the string and counts the number of words that contain at least 3 vowels. I feel as if this is a very easy code to write, but it's always the easiest things that seem to elude me. Any help?
Also: Being new to C, how can I get the same results while using the function int vowel_count(char my_sen[]) instead of using the code within my main?
If that's a tad confusing I mean since my main already contains code to count the number of vowels within my input, how can I somewhat transfer said code into this function and still call upon it in main?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define SENTENCE 256
int main(void){
char my_sen[SENTENCE], *s; //String that containts at most 256 as well as a pointer
int words = 1, count = 0,vowel_word = 0; //Integer variables being defined
int i,vowel = 0, length; //More definitions
printf("Enter a sentence: ");//Input sentence
gets(my_sen);//Receives and processes input
length = strlen(my_sen); //Stores the length of the input within length
for(i=0;my_sen[i] != '\0'; i++){
if(my_sen[i]=='a' || my_sen[i]=='e' || my_sen[i]=='i' || my_sen[i]=='o' || my_sen[i]=='u' || //Loop that states if the input contains any of the following
my_sen[i]=='A' || my_sen[i]=='E' || my_sen[i]=='I' || my_sen[i]=='O' || my_sen[i]=='U') //characters(in this case, vowels), then it shall be
{ //stored to be later printed
vowel++;
}
if(my_sen[i]==' ' || my_sen[i]=='!' || my_sen[i]=='.' || my_sen[i]==',' || my_sen[i]==';' || //Similar to the vowel loop, but this time
my_sen[i]=='?') //if the following characters are scanned within the input
{ //then the length of the characters within the input is
length--; //subtracted
}
}
for(s = my_sen; *s != '\0'; s++){ //Loop that stores the number of words typed after
if(*s == ' '){ //each following space
count++;
}
}
printf("The sentence entered is %u characters long.\n", length); //Simply prints the number of characters within the input
printf("Number of words in the sentence: %d\n", count + 1); // Adding 1 to t[he count to keep track of the last word
printf("Average length of a word in the input: %d\n", length/count);//Prints the average length of words in the input
printf("Total Number of Vowels: %d\n", vowel);//Prints the number of vowels in the input
printf("Average number of vowels: %d\n", vowel/count);//Prints the average number of vowels within the input
printf("Number of words that contain at least 3 vowels: %d\n", vowel_word);//Prints number of words that contain at least 3 vowels
return 0;
}
It's not much of a problem.
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int vowel_count(char my_sen[])
{
int wcount = 0; // number of words with 3+ vowel chars
int vcount = 0; // current number of vowel chars in the current word
int i = 0; // index into the string
int ch;
while ((ch = my_sen[i++]) != '\0')
{
if (isspace(ch) || !isalpha(ch))
{
// ch is not an alphabetical char, which can happen either
// before a word or after a word.
// If it's after a word, the running vowel count can be >= 3
// and we need to count this word in.
wcount += vcount >= 3; // add 1 to wcount if vcount >= 3
vcount = 0; // reset the running vowel counter
continue; // skip spaces and non-alphabetical chars
}
if (strchr("aeiouAEIOU", ch) != NULL) // if ch is one of these
{
++vcount; // count vowels
}
}
// If my_sen[] ends with an alphabetical char,
// which belongs to the last word, we haven't yet
// had a chance to process its vcount. We only
// do that in the above code when seeing a non-
// alphabetical char following a word, but the
// loop body doesn't execute for the final ch='\0'.
wcount += vcount >= 3; // add 1 to wcount if vcount >= 3
return wcount;
}
int main(void)
{
char sen[] = "CONSTITUTION: We the People of the United States...";
printf("# of words with 3+ vowels in \"%s\" is %d", sen, vowel_count(sen));
return 0;
}
Output (ideone):
# of words with 3+ vowels in "CONSTITUTION: We the People of the United States..." is 3
Btw, you can alter this function to count all things you need. It already finds where words begin and end and so, simple word counting is easy to implement. And word length, too. And so on.
1) Get the string,
2) use strtok () to get each words seperated by space.
3) Loop through each string by char by char to check if it is vowel.
Please check below code
#include<stdio.h>
#include <string.h>
int count_vowels(char []);
int check_vowel(char);
main()
{
char array[100];
printf("Enter a string\n");
gets(array);
char seps[] = " ";
char* token;
int input[5];
int i = 0;
int c = 0;
int count = 0;
token = strtok (array, seps);
while (token != NULL)
{
c = 0;
c = count_vowels(token);
if (c >= 3) {
count++;
}
token = strtok (NULL, seps);
}
printf("Number of words that contain atleast 3 vowels : %d\n", count);
return 0;
}
int count_vowels(char a[])
{
int count = 0, c = 0, flag;
char d;
do
{
d = a[c];
flag = check_vowel(d);
if ( flag == 1 )
count++;
c++;
}while( d != '\0' );
return count;
}
int check_vowel(char a)
{
if ( a >= 'A' && a <= 'Z' )
a = a + 'a' - 'A'; /* Converting to lower case */
if ( a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
return 1;
return 0;
}

Performing arithmetic on Characters in C

I am trying to write a program that adds, subtracts, multiplies, and divides a string of characters. Where I'm at now with the program is figuring out how to split the input string into two strings, and then perform the appropriate +-/*.
The input should look like this abc+aaa
and the output for that should be abc + aaa = bcd
How do I convert character strings into integer strings?
#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
printf("This is a pseudo arithmetic program");
char input[10];
input[10] = '\0';
char first [9];
first[9] = '\0';
char last [9];
last[9] = '\0';
int i = 0;
int b;
int e;
while (input[0] != '0') {
if (input[0] == 0){
return -1;
}
printf("\nEnter a math problem in SOS format using only lowercase letters up to 9 characters");
printf("\nEx: abc+abc... type '0' to quit \n");
scanf("%s", input);
int x = 0;
x = strlen(input);
if (strchr(input, '+')){
for (i = 0; i <= x; i++) {
if (i == '+')
strncpy(first, &input[0], i-1);
i = 0;
}
for (i = x; i >= input[0]; i--) {
if (i == '+')
strncpy(last, &input[i], x);
i = 0;
}
printf("%s", first);
printf(" + ");
printf("%s", last);
printf(" = %d", first + last);
}
There seems to be multiple problems with your code:
There is a array out of bounds happening for almost all the arrays:
char input[10];
input[10] = '\0';
In this if you want to initialize the last character with '\0' then it should be
input [9] = '\0'
Arrays indexes always start from 0.
It is not clear what is the use of below lines:
while (input[0] != '0') { if (input[0] == 0){ return -1; }
When taking input for a string, why are prompting users to enter a 0 to end it?
strrchr returns the pointer from where the searched character begins. So, you can that itself to determine where the '+' symbol is and two split the strings instead of your while loop. See strrchr man page
Also, your idea of adding characters is not clear. From your example, it appears you are considering a = 1, b = 2 etc. In such a case, if your code is case insensitive, then you can convert all your input to upper case and then do (input[0] - 'A')+1 to convert your letters like a, b, c to 1, 2, 3 etc.
Hope these pointers help. Suggest you check your problem statement again and refactor your code accordingly.

Program to show the number of characters in a string

This is a program to find the number of characters in a string. But it counts the wrong number of characters. Is it counting the white space too ? Even if that is true how can the total number be 89 ? (see output below)
#include <stdio.h>
#include <conio.h>
void occurrence(char str[100], char ch)
{
int count=0,max =0,i;
for(i=0;i<=100;i++)
{
if(str[i]!='\0')
{
max = max + 1;
if(str[i]==ch)
{
count = count + 1;
}
}
}
printf("\nTotal Number of characters : %d\n",max);
printf("\nNumber of Occurrences of %c : %d\n",ch,count);
}
int main(void)
{
void occurrence(char [], char);
int chk;
char str[100], ch, buffer;
clrscr();
printf("Enter a string : \n");
gets(str);
printf("Do you want to find the number of occurences \nof a particular character (Y = 1 / N = 0) ? ");
scanf("%d", &chk);
do
{
if (chk==1)
{
buffer = getchar(); //dummy varaiable to catch input \n
printf("Enter a Character : ");
ch = getchar();
occurrence(str,ch);
printf("\n\nDo you want to check the number of occurences \nof another character (Y = 1 / N = 0) ? ");
scanf("%d", &chk);
}
else
{
exit();
}
}
while(chk);
return 0;
}
There are two important things wrong with the for loop that counts characters:
It goes from 0 to 100, when it should go from 0 to 99. If you allocate a 100-element array, then the index of the highest element is 99, for a total of a hundred elements. Traditionally the exit condition for the loop would be i < 100, not i <= 100.
It keeps going after the '\0' is found. The '\0' character marks the end of the string, and you should not count any characters after it. Some of the characters after the '\0' may themselves be '\0's, and so you won't count them; but there could be any other kind of garbage there as well, and those will mess up your count. You must figure out how to change your for loop to exit as soon as the '\0' character is found, and not count anything else after that point.
Yes, whitespace is a character. Also are characters each of the 100 elements in your array. You are counting everything but nulls, sp I guess you have 11 nulls. Also, your for loop is off by one.
This will give you correct output.
void occurrence(char str[100], char ch)
{
int count=0,max = 0,i = 0;
while(str[i]!='\0')
{
max = max + 1;
if( str[i] == ch )
{
count = count + 1;
}
i++;
}
}

Resources