Setting last character in a string to 0 causes program crash - c

This is for a homework assignment, so it can not use loops of any kind as a way to force recursion practice. I am also not to change the method signature, or anything in the main() function.
The function is intended to use recursion to print a string in reverse. I learned on this site (Strip first and last character from C string) how to remove the last character in a string. When I try and reproduce it in my code, the program crashes on execution. Here is that code:
#include <stdio.h>
#include <string.h>
void print_reverse_str(char *str) {
if (strlen(str) == 1)
printf("%c", &str[0]);
else {
int len = strlen(str);
int lastIndex = len - 1;
char endChar = str[lastIndex];
printf("%c", &endChar);
str[lastIndex] = 0;
print_reverse_str(str);
}
}
int main() {
print_reverse_str("My string");
printf("\n");
print_reverse_str("!ti tog uoy ,siht daer nac uoy fI");
printf("\n");
}

You can not change a string literal.
Character display with printf. E.g printf("%c", character);, not &character
try this.
#include <stdio.h>
#include <string.h>
void print_reverse_str(char *str){
if (*str){
print_reverse_str(str+1);
printf("%c", *str);
}
}
int main(){
print_reverse_str("My string");
printf("\n");
print_reverse_str("!ti tog uoy ,siht daer nac uoy fI");
printf("\n");
}

Related

Why cant the loop be terminated in my code?

This a reverse string code but the loop cant be terminated and keeps taking input
How can I terminate it
#include <stdio.h>
#include <string.h>
#define len 100
int main() {
char str[len];
int i;
do {
gets(str);
for (i = (strlen(str) - 1); i > -1; i--) {
printf("%c", str[i]);
}
printf("\n");
} while (str[0] != '\0');
return 0;
add str[0]='\0'; before gets and its done. this is because making a loop termination and to get out of the loop after clicking enter.
#include <stdio.h>
#include <string.h>
#define len 100
int main() {
char str[len];
int i,lenh;
do{
str[0]='\0';
gets(str);
lenh=strlen(str);
for(i=lenh-1;i>=0;i--)
{
printf("%c",str[i]);
}
printf("\n");
}while(str[0]!='\0');
return 0;
}
now, there are a few points (answer code below)
Basically, you are printing hand-to-hand with input, while the question states of a multi line input. So, first you have to take all the inputs and then output will be shown.
Your original code does not keep taking input as you have said. Question says the last string is empty string. You press enter in empty string, your above code will terminate.
Remember Last Input String Should be Empty, that's termination condition
#include <stdio.h>
#include <string.h>
int main(){
char str[100];
char stringArray[50][100]={0};
int k,m,count=0,i=0,j=0;
do {
fgets(str,100,stdin);
k=strlen(str);
for(m=0;m<k-1;m++){
stringArray[count][k-m-2]=str[m];
}
count++;
}
while (str[0] != '\n');
for(i=0; i<count; i++){
for(j=0;stringArray[i][j]!=0;j++){
printf("%c",stringArray[i][j]);
}
if(i<count-1){
printf("\n");}
}
return 0;
}
sample input
Hello team Loop
Welcome
sample output
pooL maet olleH
emocleW

Replacing letter on string C language

i'm practicing strings now and what i try to do in this program is print something like: hello world into HellO WorlD as an output.
My code is the following one:
#include <stdio.h>
#include <string.h>
void convertir(char cadena[200]){
int length = strlen(cadena);
int i;
printf("%c", cadena[0]-32); // Prints letter in caps
for(i=1;i<length-1;i++){
if(cadena[i] == ' '){ // Search if there is space
printf("%c", cadena[i-1]-32);
i=i+1; // Adds vaule on i with accumulator to make caps the letter after the space
printf(" %c", cadena[i]-32); // prints letter in caps after space
} else {
printf("%c", cadena[i]); // prints everything in the string
}
}
printf("%c", cadena[length-1]-32);
}
int main(int argc, char const *argv[]) {
char cadena[200];
printf("Introduce un texto: ");
gets(cadena);
convertir(cadena);
return 0;
}
What the code compiled returns me after typing hello world is: HelloO WorlD, i'm trying to replace that o in HelloO but i'm getting confused...
Any help is appreciated.
Thank you.
I made the following changes to your for loop and it appears to work as you expect it to:
for(i=1;i<length-1;i++)
{
if(cadena[i + 1] == ' ') /*** Look If Next Character Is A Space ***/
{
printf("%c", cadena[i]-32); /*** Print Current Character In Uppercase ***/
i=i+1; // Adds vaule on i with accumulator to make caps the letter after the space
printf(" %c", cadena[i + 1]-32); /*** Print Character After Space In Caps ***/
i=i+1; // Adds vaule on i with accumulator to make caps the letter after the space
}
else
{
printf("%c", cadena[i]); // prints everything in the string
}
}
Output:
$ ./main.exe
Introduce un texto: hello world
HellO WorlD
Moving forward, there are several things you should do to make your program more robust:
Don't assume there aren't leading spaces (or whitespace)
Don't assume each character is lowercase
Don't assume each character is a letter
Don't assume there is only one space (or whitespace) between words
Any help is appreciated.
Use isalpha() to detect if a char is part of a word.
Use toupper() to convert to an uppercase character.
Use unsigned char for isalpha(), toupper() to avoid UB with negative char values.
Employ a boolean to keep track if a beginning of a word is possible.
#include <ctpye.h>
#include <stdbool.h>
void convertir(const char *cadena) {
const unsigned char *s = (const unsigned char *) cadena;
bool potential_start_of_word = true;
while (*s) {
// If next character is not an alpha or we area at the start of a word ...
if (!isapha(s[1]) || potential_start_of_word) {
printf("%c", toupper(*s));
} else {
printf("%c", *s);
}
potential_start_of_word = !isapha(*s);
s++;
}
}
No need for strlen(cadena)
You can use ctype.h's toupper() function or provide your own implementation. Something like this:
int toupper(int c) {
return (c-32);
}
And then use it like this:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void convertir(char cadena[200]){
int length = strlen(cadena);
int i;
cadena[0] = toupper(cadena[0]);
cadena[length-1] = toupper(cadena[length-1]);
for(i=0; i<length; i++){
if(cadena[i] == ' '){ // Search if there is space
cadena[i-1] = toupper(cadena[i-1]);
if (i+1 < length) cadena[i+1] = toupper(cadena[i+1]);
}
}
printf("%s\n", cadena);
}
int main(int argc, char *argv[]) {
char cadena[200];
printf("Introduce un texto: ");
gets(cadena);
convertir(cadena);
return 0;
}

Beginner C language: Problem with condition in while loop... same logic different result

My code should delete all vowels from the string that i give. But it does not delete if the vowel is the last character of the string.
#include <stdio.h>
#include <string.h>
int main()
{
int i=0;
char str[100];
printf("Enter a string :\n");
gets(str);
int len=strlen(str);
while(str[i]!='\0')
{
printf("%c",str[i]);
if(str[i]=='A'||str[i]=='a'||str[i]=='E'||str[i]=='e'||str[i]=='I'||str[i]=='i'||str[i]=='O'||str[i]=='o'||str[i]=='U'||str[i]=='u')
printf("\b");
i++;
}
return 0;
}
Like if i provide the string Hello it prints Hllo where it should print Hll ...But if i change the while condition to (i
I guess printing \b doesn’t do what you think it does. It does not delete the last printed character, it just prints an additional ‘backspace’ character, which on some output devices (such as console) moves backwards by one character. (Then, the next character overwrites the one you wanted ‘deleted’.)
Don’t do that. Instead, move the ‘if’ statement so that you don’t print those vowels in the first place!
You can try this
#include <stdio.h>
#include <string.h>
int main()
{
int i=0;
char str[100];
printf("Enter a string :\n");
fgets(str,100, stdin);
int len=strlen(str);
while(str[i]!='\0')
{
if(str[i]=='A'||str[i]=='a'||str[i]=='E'||str[i]=='e'||str[i]=='I'||str[i]=='i'||str[i]=='O'||str[i]=='o'||str[i]=='U'||str[i]=='u'){
continue;
}else{
printf("%c",str[i]);
}
i++;
}
return 0;
}

Print a string till a particular character comes

I want the string to be printed till character ('e') comes.
Code which I tried:-
#include <stdio.h>
int main() {
int a,i,x;
char b[10];
char ch;
//enter input string
for(i=0;i<10;i++)
scanf("%c",&b[i]);
for(i=0;i<10;i++)
if(b[i]!='e')
printf("%c",b[i]);
return 0;
}
Input:abcdefghij
Actual output:abcdfghij
Desired output:abcd
Question : Where am I wrong ? Will putting a break inside if block work here?
This is much cleaner if you want to use scanf.
#include <stdio.h>
int main()
{
char b[101];
scanf("%100s", b);
printf("%s\n", b);
return(0);
}
Or even better.
#include <stdio.h>
#define MAX_LENGTH 100
int main()
{
char b[MAX_LENGTH+1]; // add 1 for the terminating zero
scanf("%100s", b);
printf("%s\n", b);
return(0);
}
This one uses fgets to read the entire line.
#include <stdio.h>
#define MAX_LENGTH 100
int main()
{
char b[MAX_LENGTH];
fgets(b, MAX_LENGTH, stdin);
printf("%s", b);
return(0);
}
How to print a string till limit?
What code should do is use fgets().
Avoid using scanf(). Is is too easy to use wrong.
#include <stdio.h>
#include <string.h>
int main() {
char b[100];
if (fgets(b, sizeof b, stdin)) {
// If code needs to lop off the potential \n at the end
b[strcspn(b, "\n")] = '\0';
printf("%s\n", b);
}
return 0;
}
Advanced issues include how to handle excessively long input lines and error handling - not shown here.
Here is what you need to do
#include <stdio.h>
int main()
{
int a,i,x;
char b[10];
char ch;
//enter input string
for(i=0;i<10;i++)
{
scanf("%c",&b[i]);
}
for(i=0;i<10;i++)
{
if(b[i]=='e')
{
break;
}
}
return 0;
}
re
There are several mistakes!
If you are initializing your loops from 0 then you need to set the condition till i<100.
Change your format specifiers to %s.
Change your IF statement to if(b[i]!='\0').
#include <stdio.h>
int main()
{
int i;
char b[10];
for(i=0;i<10;i++)
{
scanf("%c",&b[i]);
}
for(i=0;i<10;i++)
{
if(b[i]=='e')
{
break;
}
printf("%c",b[i]);
}
return 0;
}

string rotations

#include <stdio.h>
#include <string.h>
int main()
{
char s[15];
int i,j,n,*str;
printf("Enter a string");
scanf("%s",str);
n=strlen(str);
for(i=0;i<n;i++)
{
str[n]=str[0];
for(j=0;j<n;j++)
{
str[j]=str[j+1];
}
str[n]='\0';
printf("\n %s",str);
}
return 0;
}
this program gives me all possible rotations of string
can anyone explain str[n]=str[0] and str[j]=str[j+1] meaning
instead of taking n=strlen(s) can we use n=strlen(str)
plz explain
This rotates the string. The way it does so is by moving the first character to the last place by doing str[n] = str[0] (str[n] is the string-terminating null character '\0', then shifting the whole string down one (str[j] = str[j+1]), then replacing the null at the end (str[n]='\0').
This code would, if it were using s, cause a buffer overrun if the string is longer than 14 characters. However, there's also a logic error in the code: it should be either initializing str (as a char* not int*) or scanning into s with a length bound. For instance:
scanf("%14s", s);
or
str = (char*)malloc(500);
scanf("%500s", str);
instead of taking n=strlen(s) can we use n=strlen(str)
Actually, since str is an int-pointer that is not initialized anywhere, all uses of str should be replaced by s (it's probably just a typo).
#include <stdio.h>
#include <string.h>
int main()
{
char s[15];
char tmp_var;
int i,j,n,*str;
printf("Enter a string");
scanf("%s",str);
n=strlen(str);
for(i=0;i<n/2;i++)
{
tmp_var = str[i];
str[i] = str[n-i];
str[n-i] = tmp_var;
}
printf("\n Rotated String is %s \n",str);
return 0;
}

Resources