C- While loop not working - c

#include <stdio.h>
#include <string.h>
int main(void)
{
char str1[1000];
int i, letter, space = 0;
char ch = str1[i];
printf("Enter a sentence: ");
scanf("%[^\n]s", str1);
printf("you enter %s\n", str1);
while (i != strlen(str1)) {
if (ch != ' ') {
letter++;
} else if (ch = ' ') {
space++;
}
i++;
}
printf("%d %d", letter, space);
}
My while loop isn't working and I can't seem to locate the problem. I am using the terminal in ubuntu and after printing the user string, I get a blank line. I have to use Ctrl-Z to stop the script.

Mistakes I see: using uninitialised variables - local variables do not get initialised automatically.
Another is you do not read a character from the string within the loop.
The third is the unecessary and syntactically incorrect if (ch=' ') which should have been if (ch==' ')
#include<stdio.h>
#include<string.h>
int main(void){
char str1[1000];
int i = 0, letter = 0, space = 0; // initialise all to 0;
printf("Enter a sentence: ");
scanf("%[^\n]s",str1);
printf("you enter %s\n",str1);
while (i!=strlen(str1)){
char ch = str1[i]; // move this inside the loop
if (ch!= ' '){
letter++;
}else { // unnecessary - you already checked space
space++;
}
i++;
}
printf("%d %d\n", letter, space);
}
Program session:
Enter a sentence: hallo my friend
you enter hallo my friend
13 2

You need to initialize i to 0 at the beginning of the program.
int i,letter,space = 0;
the above line will only set space to 0 and not i.

This shall work :
int i = 0;
int letter = 0;
int space = 0;
char ch = ' ';
printf("Enter a sentence: ");
scanf("%[^\n]s",str1);
printf("you enter %s\n",str1);
while (i!=strlen(str1)){
ch = str1[i];
if (ch!= ' '){
letter++;
} else {
space++;
}
i++;
}

You need to initialise i to 0 before entering the loop. Also if (ch=' ') should be if (ch==' '). Next time, try to compile with warnings enabled (-Wall -Wextra).
Also, while probably not related to the issue here, using strlen() in a condition of a while statement can be a performance disaster if the string is too long. Furthermore, do note that the scanf() function may write beyond the end of the buffer if the input string is too long. For this specific case, I recommend getting the string using getline() (which dynamically allocates the necessary buffer).

Related

why does the statements inside loop condition execute when condition is false in c programming?

I am just running a code to find the length of a given string input by the user in C programming language. I used a loop condition to determine the length but statements inside loop executes when the condition is false also. The code I have tried in c is:
#include <stdio.h>
#define ArrayLength 50
int StringLengthCount();
int main() {
printf("Hello, World!\n");
/*Question: Find inserted string's length, without build in function*/
int c=StringLengthCount();
printf("Your inserted string's length is:%d",c);
return 0;
}
int StringLengthCount(){
printf("\n");
printf("Please enter a sentence to find its length of character:");
char array1[ArrayLength];
fgets(array1,ArrayLength,stdin);
printf("Your inserted string is:%s\n",array1);
int i=0;
int count=0;
while(array1[i]!='\0'){
count++;
printf("%d character is %c",count,array1[i]);
printf("\n");
i++;
}
printf("\n");
printf("Your inserted string's total character i.e string length is:%d",count);
}
I am expecting the result 2 for a sample string input "we", but it gives result 3.
The output result in CLion compiler is given below
enter image description here
Can you kindly tell me why it happens?
If by "statements inside loop executes when the condition is false also" you mean that you see an extra character every time you execute remember that also the line feed (LF alias \n) character that you use to enter your string is part of the acquired string.
So even the empty string has one character that is \n or 0x10.
Your check should be something like this:
while (array1[len] != '\0' && array1[len] != '\n' )
And you function, as suggested in the comments, should have a return and could use just one variable like this:
int StringLengthCount() {
printf("\n");
printf("Please enter a sentence to find its length of character:");
char array1[ArrayLength];
fgets(array1, ArrayLength, stdin);
printf("Your inserted string is:%s\n", array1);
int len = 0;
while (array1[len] != '\0' && array1[len] != '\n' ) {
printf("%d character is %c", len + 1, array1[len]);
printf("\n");
len++;
}
printf("\n");
printf("Your inserted string's total character i.e string length is:%d\n\n",
len);
return len;
}
The function fgets will also read the newline character, so you need to change the condition in the while-loop from str[i] != '\0' to str[i] != '\n'. I have also implemented the suggested changes by Devolus.
#include <stdio.h>
#include <stdlib.h>
#define LEN 50
void string_length();
int main(void)
{
string_length();
return EXIT_SUCCESS;
}
void string_length(void)
{
printf("Enter a string: ");
char str[LEN];
fgets(str, LEN - 1, stdin);
printf("Your entered string is: %s\n", str);
int i = 0;
while (str[i] != '\n') {
printf("The %d. character is '%c'.\n", i + 1, str[i]);
++i;
}
printf("\nThe string's length is %d.\n", i);
}

i want to remove spaces from a string to check if its palendrome but it keeps adding letters in C

the issue i have is that the code keeps adding letters after the 'for' code, if i write "ni pratar bra latin" it will become "nipratarbralatintin" with an exta "tin"
int ret1;
int size = 0;
int i = 0;
char ch[100];
printf("WELCOME USER\n");
printf("ENTER A SENTENCE OR A WORD FOR THE PROGRAM TO START.\n");
printf("THE PROGRAM WILL CHECK IF YOUR SENTENCE / WORD IS A PALENDROME");
printf("\n");
scanf(" %[^\n]s", &ch);
Removes spaces aka the part im having issues with
for (i = 0, size = 0; i < strlen(ch); i++) {
ch[i - size] = ch[i];
if (ch[i] == ' ')
size++;
}
ch[i] = '\0';
ret1 = isPalindrome(ch);
int quit;
if (ret1 == 1)
// 1 means string is palendrome
printf("\nYOUR SENTENCE/WORD: %s IS A PALENDROME", ch);
else if (ret1 == 0)
// 0 means string is not palendrome
printf("\nYOUR SENTENCE/WORD: %s IS NOT A PALENDROME", ch);
The line
ch[i] = '\0';
is wrong. The line is meaningless because \0 will already be there on ch[i] because it is after exiting the loop with the condition i < strlen(ch).
The line should be
ch[i - size] = '\0';
to maintain consistency with the line inside the loop ch[i - size] = ch[i];.
Also the line
scanf(" %[^\n]s", &ch);
is wrong because char(*)[100] is passed where char* is expected and undefined behavior is invoked.
It should be
scanf(" %[^\n]s", ch);
without the extra &.
This version with checking is better:
if (scanf(" %[^\n]s", &ch) != 1) {
fputs("read error\n", stderr);
/* exit program (return from main(), using exit(), etc. */
}

String length prints weird numbers. Where is the issue in my code?

My task is: Write a program that calculates the length of a string without using the library
This is my answer, but there is a problem with execution. The length doesnt show properly ! the execution shows length as 107 or 127 for any string I insert.
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Declaration of variables :
char ch[50+1];
int length, i;
//data :
printf("ch : ");
scanf("%s", &ch);
printf("\n");
//Search length of string :
i = 0;
do
{
if(ch[i] == '\0')
{
length = i;
}
else
{
i++;
}
}
while(ch[i] != '\0');
//Result "
printf("length pf %s is : %d \n", ch, length);
return 0;
} ```
There is a problem with the algorithm of the do-while loop.
The counter i increments short before the condition check.
If '\0' is found in the next array element (Note, that i is incremented) the loop breaks immediately and won´t be able to set length to i at the next iteration (because there is no next iteration).
Since length is not initialized, the program has undefined behavior.
Change:
do
{
if (ch[i] == '\0')
{
length = i;
}
else
{
i++;
}
}
while (ch[i] != '\0');
to
while (ch[i] != '\0') i++;
length = i;
or even simpler:
while (ch[i] != '\0') length++;
and omit the counter i, but you need to initialize length by 0 then.
Side Notes:
Change scanf("%s", &ch); to scanf("%s", ch);. - ch decays to a pointer to its first element.
Use a length modifier at scanf() -> scanf("%50s", ch); to ensure that no buffer overflow occurs when the user inputs a string longer than 50 characters.
Always check the return value of scanf() if an error occurred at consuming input.
Never ignore at the compiler warnings. For scanf("%50s", ch); the compiler should have raised a warning.

Copying input to output without unnecessary Spaces in C

I'm trying to write a program in C that copies its input to its output while replacing each string of one or more Spaces with a single Space.
My code isn't doing that but is instead taking away every second character.
This is my code:
#include <stdio.h>
main()
{
int c;
int lastc;
lastc = 0;
while(getchar() != EOF){
c = getchar();
if(c == 32 && lastc == 32)
;
else
putchar(c);
lastc = c;
}
}
Your loop should look like:
while((c = getchar()) != EOF){
if(c == 32 && lastc == 32)
;
else
putchar(c);
lastc = c;
}
In your version you get a char with getchar while checking the condition for the while loop and then as a next step you again get a char with getchar. So the first one is not used in your code. Therefore it is taking away every second character.
Keep running in while loop until you get non-space character and print just one space after you get out.
int main()
{
int c;
bool space=false;
while ((c=getchar()) != EOF) {
while (isspace(c)) {
space = true;
c = getchar();
}
if (space) {
putchar(' ');
space = false;
}
putchar(c);
}
return 0;
}
I use fgets() function to getting string from input i.e stdin and store in the scroll string.
Then you must implement a way to analyze string to find spaces in it.
When you find first space, increase index if you face another space.
This is the code.
Code
#include <stdio.h>
int main(void){
char scroll[100];// = "kang c heng junga";
fgets(scroll, 100, stdin);
printf ("Full name: %s\n", scroll);
int flag = 0;
int i=0;
while (scroll[i] != '\0')
{
if (scroll[i] == ' ' )
flag=1;//first space find
printf("%c",scroll[i]);
if (flag==0){
i++;
}else {
while(scroll[i]==' ')
i++;
flag=0;
}
}
return 0;
}
Sample input: Salam be shoma doostane aziz
Program output: Salam be shoma doostane aziz
[Edit]
Use new string st to hold space eliminated string an print as output.
Also this code work for Persian string.
char scroll[100]={0};// = "kang c heng junga";
printf("Enter a string: ");
fgets(scroll, 100, stdin);
printf ("Original string: %s\n", scroll);
char st[100]={0};
int flag = 0;
int i=0;
int j=0;
while (scroll[i] != '\0')
{
if (scroll[i] == ' ' )
flag=1;//first space find
st[j]=scroll[i];
j++;
if (flag==0){
i++;
}else {
while(scroll[i]==' ')
i++;
flag=0;
}
}
printf("Eliminate Spaces: %s", st);

How can I replace getchar();?

#include <stdio.h>
int main (void)
{
int n;
printf("Give the number of words you want to input.");
scanf("%d",&n);
int letters[n],i,j,count,key,k;
char str[100];
//Scans each word, counts it's letters and stores it in the next available
//position in "letters" array.
for (i=0;i<n;i++)
{
j=0;
printf("Give the next word.");
do{
str[j] = getchar();
j++;
}while (str[j-1]!='\n');
str[j-1] = '\0';
letters[i] = j;
}
//Compacts the data by figuring out which cells have the same number of letters
for (i=0;i<n;i++)
{
key = letters[i];
count = 0;
for (j=i+1;j<=n;j++)
{
if (key==letters[j])
{
count += 1;
letters[j] = 0;
}
}
letters[i] = count;
}
//creates a histogram
i=0;
do{
printf("%d|",i);
for (j=1;j<=letters[i];j++)
{
printf("*");
}
printf("\n");
i++;
}while ((i<=n));
return 0;
}
I understand that getchar(); reads, the first enter (\n) , user hits, to give the amount of words he wants to input, and thus expects one less word.
Also, I get an infite loop for some reason at the end. Any help and ideas would be appreciated. Thanks in advance.
Change the first block of your code to look like this:
(test the output of getchar, and continues only if not EOF)
for (i=0;i<n;i++)
{
j=0;
printf("Give the next word.");
do{
a = getchar();
if(a >= 0)
{
str[j] = a;
j++;
}
else break;
}while (str[j-1]!='\n');
str[j-1] = '\0';
letters[i] = j;
}
But regarding your question: How can I replace getchar();? Have you considered using scanf()?
EDIT
Here is a simple example of using scanf() and printf() to prompt for input and then display input. It will allow user to input entire words or sentences (up to 80 characters) until 'q' is entered. Not exactly what you are doing, but you should be able to adapt it to your code... (run this)
int main(void)
{
char buf[80]={""};
while( strcmp(buf, "q") != 0) //enter a 'q' to quit
{
buf[0]=0;
printf("enter string:\n");
scanf("%s", buf);
printf("%s\n", buf);
}
}
Wouldn't it be easier to update the letter count in the first loop?
memset(letters, 0, n);
for (i=0;i<n;i++)
{
char* s = str;
int j=0;
printf("Give the next word.");
do{
*s = getchar();
++j;
}while (*(s++)!='\n');
s[-1] = '\0';
letters[j-1]++;
}
As a result the second loop will be unnecessary.
The following two lines have the wrong end condition; should be <n, not <=n. Currently they retrieve an uninitialized array element. Since you declared str as a local variable, that element is typically populated with garbage, i.e. a very big random number. That might explain why it takes extreme long (but possibly not forever) for the last loop to finish.
for (j=i+1;j<=n;j++)
}while ((i<=n));
Also, I assume line n of the histogram should contain the number of words that have n letters? That's not what you're doing right now.
letters[i] = count;
That line should have been:
letters[key] = count;
But to make that work, you should not overwrite the same array letters; you must declare a new array for your histogram, otherwise the second loop will destroy its own input.
By the way, str seems totally redundant. Is it there for debugging purposes?

Resources