Reading and reversing string using getchar in C - c

New C coder here. I'm not certain why, but my program gets stuck in the first while loop and will not move on to the other code. Does anyone have any idea what's wrong?
#include <stdio.h>
int main(void){
char str[20];
char reverse[20];
int c;
int i;
int j;
int k;
printf("Enter a string: ");
i=0;
j=0;
while((i<20)&&((c=getchar())!='\n')){
str[i] = c;
i++;
}
k=i;
while((j<k)&&(i>=0)){
reverse[j]=str[i];
j++;
i--;
}
printf("\n");
if(i==0){
while(i<k){
putchar(reverse[i]);
}
}else{
printf("logic error");
}
return 0;
}
Thank you!

#include<stdio.h>
void reverse(void)
{
char c;
if((c = getchar()) != '\n'){ reverse(); }
putchar(c);
return;
}
int main(void)
{
printf("Enter a line of text below:n");
reverse();
putchar('\n');
}

Your code don't get stuck in the first while. It gets stuck here:
while(i<k){
putchar(reverse[i]);
}
because you never change i or k, i.e. an endless loop.
Try this instead:
while(i<k){
putchar(reverse[i]);
++i;
}
Another problem is that you reverse one character past the input as i has been incremented to index the "next free char" . Don't do that.
Instead of:
while((j<k)&&(i>=0)){
reverse[j]=str[i];
j++;
i--;
}
try:
while(i>=0){
reverse[j]=str[i-1]; // Notice the -1
j++;
i--;
}
++i;
Putting it all together, it will be:
int main(void){
char str[20];
char reverse[20];
int c;
int i;
int j = 0;
int k;
printf("Enter a string: ");
i=0;
j=0;
while((i<20)&&((c=getchar())!='\n')){
str[i] = c;
i++;
}
k=i;
while(i >= 0){
reverse[j]=str[i-1]; // Notice
j++;
i--;
}
++i; // Notice
printf("\n");
if(i==0){ // This if-statement is nor really needed - just remove it
while(i<k){
putchar(reverse[i]);
i++; // Notice
}
}else{
printf("logic error");
}
printf("\n");
return 0;
}

Related

I want to change the output value of the string

#include <stdio.h>
int main() {
char str[101];
int i;
int j=1;
scanf("%s", str);
for(i=0; str[i]!='\0'; i++) {
if(i!=0 && i%j==0) {
printf("\n");
j++;
}
printf("%c", str[i]);
}
}
If I input "abcdefg" in this code, I want it printed in turn like stairs.
a(\n)
bc(\n)
def(\n)
g
How fix code?
Try:
#include <stdio.h>
int main() {
char str[101];
int i;
int j=1,k=0;
scanf("%s", str);
for(i=0;str[i]!='\0';i=k+i)
{
for(j=i;j<=i+k && str[j]!='\0';j++)
printf("%c", str[j]);
k++;
if(str[j]!='\0')
printf("\n");
}
}
This could fix your problem
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j=1,k;
char str[100];
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
{
for(k=0;k<j;k++)
{
if(str[k+i]!='\0')
printf("%c",str[k+i]);
else
exit(1);
}
printf("\n");
j++;
i=k+i-1;
}
return 0;
}

Trying to remove substring from string in C, keep failing

I know this question has been asked many times before but I simply cannot get my head around what I am doing wrong. Everytime I make some progress I get a new error. The code I am using is really basic because I am a newbie and our professor requires the usage of scanf and gets. This is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
int identify(char[], char[]);
int remove(char[], char[], int);
int scan(choice)
{
while(choice < 0 || choice > 7)
{
printf("Invalid input, choose again\n");
scanf("%d", &choice);
}
return choice;
}
int main()
{
char sentence[MAX_SIZE], word[MAX_SIZE];
int choice, i, j, k, deikths;
printf("Choose one of the following:\n");
printf("1. Give sentence\n");
printf("2. Subtract a word\n");
printf("3. Add a word\n");
printf("4. Count the words\n");
printf("5. Count the sentences\n");
printf("6. Count the characters\n");
printf("7. Is the phrase a palindrome?\n");
printf("0. Exit\n");
scanf("%d", &choice);
if(scan(choice) == 1)
{
printf("Give sentence:\n");
gets(sentence);
gets(sentence);
printf("%s\n", sentence);
}
else(scan(choice) == 2);
{
printf("Give word you want to subtract\n");
gets(word);
printf("%s", word);
deikths = identify(sentence, word);
if(deikths != -1)
{
remove(sentence, word, deikths);
printf("Sentence without word: %s\n", sentence);
}
else
{
printf("Word not found in sentence.\n");
}
}
}
int identify(char sentence[], char word[])
{
int i, j, k;
for(k = 0; word[k] != '\0'; k++);
{
for(i = 0, j = 0; sentence[i] != '\0'; i++)
{
if(sentence[i] == word[j])
{
j++;
}
else
{
j = 0;
}
}
}
if(j == 1)
{
return(i - j);
}
else
{
return -1;
}
}
int remove(char sentence[], char word[], int deikths)
{
int i, k;
for(k = 0; word[k] != '\0'; k++)
{
for(i = deikths; sentence[i] != '\0'; i++)
{
sentence[i] = sentence[i + k + 1];
}
}
}
The error I am getting, is that the remove function has conflicting types. Any help with fixing my code will be greatly appreciated, or even an alternative solution to my problem would bre great.
As established in the comments, the compiler error is generated because remove is already defined in the stdio.h. After changing, the name the code compiles successfully, but still doesn't work as expected.
identify is the function which is meant to find whether a substring exists in a string and return its position. This is very similar to how strstr from the standard library works - I'd suggest having a look at an implementation of that function, to better understand how this is done.
The function you implemented only correctly finds substrings of length 1, at the end of the string. I have highlighted errors in the code below which cause this.
int identify(char sentence[], char word[])
{
int i, j, k;
for(k = 0; word[k] != '\0'; k++); // <- this loops is never actually ran because of the trailing semicolon - this is however a good thing as it is redundant
{
for(i = 0, j = 0; sentence[i] != '\0'; i++)
{
if(sentence[i] == word[j])
{
j++;
}
else
{
j = 0; // <- this makes it so only matches at the end can be found - otherwise, j is just reset back to 0
}
}
}
if(j == 1) // <- this makes it so only matches of length 1 can be found
{
return(i - j); // <- this is only correct if the match is at the end of the sentence
}
else
{
return -1;
}
}
strremove is inefficient due to the nested loops and the range of characters copied needs to be shortened - right now data is access beyond the end of the array.
int strremove(char sentence[], char word[], int deikths)
{
int i, k;
for(k = 0; word[k] != '\0'; k++) // <- this loop is redundant
{
for(i = deikths; sentence[i] != '\0'; i++) // <- you need to add range checking to make sure sentence[i+k+1] doesn't go beyond the end of the string
{
sentence[i] = sentence[i + k + 1];
}
}
}
I will leave the problems in main as an exercise to you - this is an assignment after all.

Trying to introduce blanks in regular interval in a string

I tried to write a function that inserts space at regular intervals in a string.
If a[50] is a string, and n is the preferred interval from the user,
insert_space(a,b,len,n) will insert blanks after the n'th column and will store the modified string in b.
#include <stdio.h>
int getinput(char temp[]);
void insert_space(char s1[],char s2[],int,int);
int main ()
{
int n, len;
char a[100], b[100];
printf("Enter the nth column number for inserting\n");
scanf("%d",&n);
printf("Enter the line\n");
len=getinput(a);
insert_space(a,b,len,n);
printf("%s\n",b);
}
void insert_space(char s1[],char s2[],int len, int n)
{
int i=0, c=0,flag=0;
for(i=0;i<=len;i++)
{
if(flag!=n)
{
s2[c]=s1[i];
c++;
flag++;
}
else
{
s2[c]=' ';
i=i-1;
c++;
flag=0;
}
}
s2[c]='\0';
}
int getinput(char temp[])
{
int c, i=0;
while((c=getchar())!=EOF)
{
temp[i]=c;
i++;
}
i--;
temp[i]='\0';
return i;
}
I entered the values of the string a as abcdefghijkmnop. Instead of
"abdce fghij kmnop" as the ouput in b, I got "abcd efghi jkmno p" as the output. I'm not sure what I did wrong here.
edit: After just including the insert_function code, I've edited it to include the entire execution code.
There is a \n ,newline (Enter) from scanf("%d",&n); which is recorded as a[0]. So you have to manage this UN-handled newline (Enter).
To solve this, add an extra c = getchar(); before loop while ((c = getchar()) != EOF) in function int getinput(char temp[]), to handle that extra newline left behind by scanf("%d",&n);
Modified code:-
#include <stdio.h>
int getinput(char temp[]);
void insert_space(char s1[], char s2[], int, int);
int main()
{
int n, len;
char a[100], b[100];
printf("Enter the nth column number for inserting\n");
scanf("%d", &n);
printf("Enter the line\n");
len = getinput(a);
insert_space(a, b, len, n);
printf("%s\n", b);
}
void insert_space(char s1[], char s2[], int len, int n)
{
int i = 0, c = 0, flag = 0;
for (i = 0; i <= len; i++)
{
if (flag != n)
{
s2[c] = s1[i];
c++;
flag++;
}
else
{
s2[c] = ' ';
i = i - 1;
c++;
flag = 0;
}
}
s2[c] = '\0';
}
int getinput(char temp[])
{
int c, i = 0;
c = getchar(); // to handle extra newline from scanf
while ((c = getchar()) != EOF)
{
temp[i] = c;
i++;
}
i--;
temp[i] = '\0';
return i;
}
Output :-
Enter the nth column number for inserting
5
Enter the line
abcdefghijkmnop
abcde fghij kmnop

Segmentationfault error

I'm trying to compile this program in Linux with a makefile but the output shows
make: ***[run] segmentation fault
My code is:
int removeblanks(char string[], char temp[]){
int i, j=0; printf("no");
while(string[i] != '\0'){
if (string[i] != ' ') {
temp[j] = string[i];
printf("%c\n",temp[j]);
j++;
}
i++;
}
temp[j] = '\0';
return i;
}
int palindromos(int size, char temp[]) {
int i,palindromo=1; int middle= size/2;
for(i=0; i<middle; i++) {
if(temp[i]!=temp[size]){
palindromo= 0;
}
size--;
}
return palindromo;
}
int main() {
char string1[30] ="Anotaram a data da maratona";
char string2[30]="A torre da derrota";
char temp1[30];
char temp2[30];
printf("frase 1: %s\n", string1);
printf("frase 2: %s\n", string2);
int size1=0;
size1=removeblanks(string1,temp1);
printf("size1: %d",size1);
int size2=removeblanks(string1,temp1);
int palindromo1=palindromos(size1, string1);
int palindromo2=palindromos(size2, string2);
printf("As frases sao palindromos.\n");
printf("As frases nao sao palindromos.\n");
return 1;
}
I don't know how to debug and find the error. Can someone help me?
In function int removeblanks(char string[], char temp[])-
int i, j=0; printf("no"); // i declared not initialized
while(string[i] != '\0'){ // uninitialized local variable used here
...
}
You should initialize i=0 before using it.

Program that finds the biggest space between two appears of the entered character

So I made a program and it doesn't work right, and I wanted to see if anyone can help me. Maybe even the idea is not right, I'm not sure.
It should find the biggest space between two appears of the provided character, and print it, or if that character doesn't appear at least 2 times, print 0.
#include <stdio.h>
main()
{
int i=0,k=0,max,a[50],j;
char n,c;
printf("Insert the character:\n");
scanf("%c",&n);
while ((c=getchar()) != EOF)
{
if (c==n)
{
c=getchar();
while (c != n)
{
k++;
c=getchar();
}
a[i]=k;
k=0;
i++;
}
}
max=a[0];
for (j=1; j<i; j++)
if (a[j]>max) max=a[j];
if (max>=2) printf("%d\n",max);
else printf("0\n");
}
Initialize max and a[0].
Check for EOF in inner while loop.
#include <stdio.h>
int main()
{
int i=0,k=0,max,a[50],j;
char n,c;
a[0] = 0; // Initialize a[0]
max = 0; // Initialize max
printf("Insert the character:\n");
scanf("%c",&n);
int end_reached = 0;
while ((c=getchar()) != EOF)
{
if (c==n)
{
c=getchar();
while (c != n)
{
if(c == EOF) { // Check for EOF
end_reached = 1;
break;
}
k++;
c=getchar();
}
if(!end_reached) { // Store k in a only if end was not reached.
a[i]=k;
k=0;
i++;
}
}
}
max=a[0];
for (j=1; j<i; j++)
if (a[j]>max)
max=a[j];
if (max>=2)
printf("%d\n",max);
else
printf("0\n");
}

Resources