Why the loop stops before it's end? - c

#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(void)
{
string name = get_string();
for(int i=0;i<strlen(name);i++ )
{
//printf("%c\n",name[i]);
if(name[i]=='\0' && name[i+1]!='\0') //try to print the next char of space
{
if(name[i+1]<='z' && name[i+1]>='a')
{
printf("%c",name[i+1]);
}
if(name[i+1]<='Z' && name[i+1]>'A')
{
printf("%c",name[i+1]);
}
}
else;
}
}
get_string() is to get users input as a string.
After I run this, it only print the first char that I input,which means the loop stops.
Is there anything wrong with my conditon lines?
after I change for(int i=0;i<strlen(name);i++ ) to for(int i=0;i<strlen(name)-1;i++ ),it gives me a Segmentation fault. I will look into it more.

Now I know why.
I thought '\0' equals ' ' ,and they are both the end of a string and space,which is very wrong.
All because of my bad english. I learnt it wrong from very begaining.
Stupid question.But I don't want to delete it,since maybe someone like me can use it.
This is my final answer.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
void caps(char x);
int main(void)
{
string name = get_string();
if (name!=NULL){
for(int i=0;i<strlen(name);i++)
{
// printf("%c\n",name[i]);
if(i==0&&name[0]!=0)
{
caps(name[0]);
}
if(name[i]==' '&& name[i+1]!=' ') //try to print the next character
{
caps(name[i+1]);
}
}
}
}
void caps(char x)
{
if(x<='z' && x>='a')
{
printf("%c",x-('a'-'A'));
}
if(x>='A' && x<='Z')
{
printf("%c",x);
}
}

Related

strcmp not working in c

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
struct Position
{
char* x1[2];
char* x2[2];
};
int main(void)
{
struct Position positions[4];
struct Position p1[4];
char* p;
matrix[10][10];
if(r==0) //stores horizontal words in matrix
{
emptyH=0;
do
{
x=(rand()%size);
y=(rand()%10);
emptyH=0;
for(k=0;k<ans;k++)
{
if ( matrix[y][x+k]!='1')
{
emptyH=1;
k=ans;
} // checks whether word fits in matrix and position is empty
}
}while(emptyH);
token = strtok(words[random],search); //strtok to seperate char by char
matrix[y][x]=token;
if(x!=0)
{
p=(char)x;
p1[i].x1[0] = p;//SAVING the positions of x and y
}
else
p1[i].x1[0]='\0';
if(y!=0)
{
p=(char)y;
p1[i].x1[1]=p;
}
else
p1[i].x1[1]='\0';
x++;
while(token!=NULL)
{
token = strtok(NULL, search);
if(token!=NULL)
{
matrix[y][x]=token;
p=(char*)x;
p1[i].x2[0]=p;
p=(char*)y;
p1[i].x2[1]=p; // saving positions of x and y
x++;
positions[i] = p1[i];
}
}
}
correct=0;
do
{
puts("\nenter the word:");
scanf("%s",&name);
printf("\n Enter the start and end position of the word");
puts("\nstart:");
scanf("%s",&start);
puts("\n\tend:");
scanf("%s",&end);
for(k=0;k<4;k++)
{
if((strcmp(positions[k].x1,start)==0)&&(strcmp(positions[k].x2,end)==0))
{
puts("viola!");
correct=1;
}
else
puts("incorrect answer! try again");
}
}
while(correct!=1);
}
this is my code. however string compare always gives wrong answer.also
sometimes there is a runtime error as i store the positions in the
'p1[i].x1[0]'. any ideas why? thankyou for your help in advance.
You are not setting up your pointers properly. You do this:
p1[i].x1[0]='\0';
So you are initializing x1[0] to point to the zero address. That's bad. You need to allocate some space and init x1[0] to point to that space.
You could add:
p1[i].x1[0] = malloc(sizeof(char)); // Now x1[0] points to some allocated space.
and then you could dereference x1[0] properly:
*(p1[i].x1[0])='\0';

I have an issue with printing a string

I'm writing a program in c to delete extra spaces,I've done all the work but when I compile, the string I want in the output doesn't appear, I think the problem is in the main function, I'll show you my code:
#include <stdio.h>
#include <stdlib.h>
void eliminar_espacios(char oracion[100]) {
int i;
for(i=0;i!='\0';i++) {
if(oracion[i]==' ' && (oracion[i+1]==' ' || oracion[i+1]=='\0')) {
oracion[i]=oracion[i+1];
}
}
}
int contar_espacios(char oracion[100])
{
int i,numero_espacios=0;
for (i=0;oracion[i]!='\0';i++){
if (oracion[i]==' '&&oracion[i+1]==' '){
numero_espacios+=1;
}
}
return(numero_espacios);
}
int main(void){
char frase[100];
int num_espacios;
printf("Escribe aqui a frase:");
gets (frase);
num_espacios=contar_espacios(frase);
eliminar_espacios(frase);
printf("%s\n",frase);
printf("%d",num_espacios);
return 0;
}
Your eliminar_espacios function has no 'return'.
Also you should use strcpy or strncopy to save new string in 'frase2',
for example:
strncpy(frase2, eliminar_espacios(frase), sizeof frase2)
Try:
strncpy(frase2, frase, 100);
frase2[99] = '\0';
eliminar_espacios(frase2);
num_espacios=contar_espacios(frase2);
Edit: If you want, you can get rid of frase2 entirely, just call all the functions with frase and no strcpy needed:
eliminar_espacios(frase);
num_espacios=contar_espacios(frase);
printf("%s\n",frase);
Edit2: Fix your eliminar_espacios() function:
void eliminar_espacios(char oracion[100]) {
int i;
for(i=0;oracion[i]!='\0';i++) {
if(oracion[i]==' ' && (oracion[i+1]==' ' || oracion[i+1]=='\0')) {
oracion[i]=oracion[i+1];
}
}
}

How to omit quotation marks usage in char type?

I'm having a really hard time adjusting function to my needs. First of all look at those three files and notice how I have to call f_texture function in main function in order to make it work:
externs.h
#ifndef EXTERNS_H_
#define EXTERNS_H_
extern char t_about[100];
extern int friction;
extern int f_texture(char* ,char*);
#endif
functionA.c
#include <stdio.h>
#include "externs.h"
int main()
{
f_texture("rough","friction");
printf("Friction: %d\n", friction);
f_texture("rough","t_about");
return 0;
}
functionB.c
#include "externs.h"
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
char t_about[100];
int friction;
int f_texture(char* texture,char* what_is_needed)
{
/*Checking if both values are present*/
assert(what_is_needed);
assert(texture);
/*Static array in order to prevent it's disappearance*/
memset(t_about, '\0', sizeof(t_about));
/*Configuring variables for desired texture*/
if (strcmp(texture, "smooth") == 0)
{
strcpy(t_about, "The surface is perfectly smooth, without any "
"protuberances.\n");
friction = 0;
}
else if (strcmp(texture, "rough") == 0)
{
strcpy(t_about, "Rough bumps can be feeled under my fingertips.\n");
friction = 4;
}
/*In case of absent keyword of desired texture it will crash the program*/
else
{
assert(!what_is_needed);
}
/*Returning desired value*/
if (strcmp(what_is_needed, "t_about") == 0)
{
int i=0;
while (t_about[i] != '\0')
{
printf("%c", t_about[i]);
i++;
}
}
else if (strcmp(what_is_needed, "friction") == 0)
{
return friction;
}
/*In case of absent keyword of desired value it will crash the program*/
else
{
assert(!what_is_needed);
}
return 0;
}
And now here is my question: How to rewrite this code to make it possible to call f_texture function without using quotation marks inside? I mean instead of f_texture("abcd","efgh") just to type f_texture(abcd,efgh). I've noticed that this way it's required just after I've wrote this code.
Thanks in advance.
If you don't want to assign string constants to variables or preprocessor object macros, another option is to use preprocessor function macros, using the stringification feature:
#define call_f_texture(a,b) f_texture(#a,#b)
....
call_f_texture(rough,friction);
The C preprocessor will turn this into
f_texture("rough","friction");
You can also use some macros:
#define ROUGH "rough"
#define FRICTION "friction"
#define T_ABOUT "t_about"
int main()
{
f_texture(ROUGH, FRICTION);
printf("Friction: %d\n", friction);
f_texture(ROUGH, T_ABOUT);
return 0;
}
You can do like this,
char rough[]="rough";
char friction[]= "friction";
and call
f_texture(rough, friction);
char a[MAX] = "rouch";
char b[MAX} = "friction";
int main()
{
f_texture();
...
}
int f_texture()
{
/*Checking if both values are present*/
assert(b);
assert(a);
}
or
int f_texture(char* a,char* b)
{
/*Checking if both values are present*/
assert(b);
assert(a);
...
}
int main()
{
char a[MAX] = "rouch";
char b[MAX} = "friction";
f_texture(a,b);
...
}

Why do i get this runtime error in this C programme? Please show me what's wrong

The task can be found here: http://www.talentbuddy.co/challenge/51846c184af0110af3822c32
And my programme regarding this task is the following:
#include <stdio.h>
#include<string.h>
void tokenize_query(char *query, char *punctuation) {
int i,j,ok=1,k,t;
char x[1000];
for(i=0;i<strlen(query);i++)
{
ok=1;
for(j=0;j<strlen(punctuation);j++)
{
if(query[i]==punctuation[j] || query[i]==' ')
ok=0;
}
if(ok!=0)
{
x[k]=query[i];
k++;
}
else {
for(t=0;t<k;t++)
{
printf("%c",x[t]);
}
k=0;
printf("\n");
}
}
}
k is uninitialised in the line
x[k]=query[i];
so you'll probably try to write beyond the end of the memory allocated for x.
The easiest fix is to initialise k when you declare it
int i,j,ok=1,k=0,t;
// ^^

Making y[i] a modifiable variable in C

I am building a program that randomly generates a password using the ascii tabe of values and can only contain one of each char. it generates a password that is 8 char long.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define SIZE 10
char Charactor(char x);
void Check(char* y);
int main()
{
char string[SIZE];//defines varriables
char* point;
point=&string[SIZE];
srand(time(NULL));
for (int i=0;i<SIZE-1;i++)//empties out the string
{
string[i]='\0';
}
for (int i=0;i<SIZE-2;i++)//randomizes a char for each space in the string
{
string[i]=Charactor(*point);
}
Check(point);/checks the string for duplicated values
printf("%s\n",string);//prints string on screen
}
char Charactor(char x)
{
int rnd=0;
rnd=rand()%2;//chooses char or number using ascii
if (rnd==0)
{
rnd=rand()%10+48;
}
else
{
rnd=rand()%26+65;
}
x=(char)rnd;
return x;
}
void Check(char* y)
{
int run=0;
for (int i=0; i<SIZE-2;i++)
{
for (int x=0; x<SIZE-2; x++)
{
if (y[i]==y[x] && run=0)
{
run++;
continue;
}
else
{
y[i]='\0';
y[i]=Charactor(*y);
}
}
}
return;
}
with those changes the code is running now I just have to figure out how to change the correct value so I dont have any duplication.
Fix:
char* point =&string[0]; //Make it to point to first element
Since your Charactor(*point); is really not doing anything based on *point and later you use Check(point); probably to start a scan from start of string.
And
if (y[i]==y[x] && run==0)
^^Use Equality check
You cannot modify a boolean outcome of y[i]==y[x] && run as zero.
Note :
However if (y[i]==y[x] && (run=0) ) wouldn't have thrown this error.
Your error seems to be that you are mistakenly setting run=0 in
if (y[i]==y[x] && run=0)
This is the part that most likely confuses your compiler. Doesn't have to do anything with Y.
Fix to:
if (y[i]==y[x] && run==0)

Resources