This program is intended to return a string, when passing command line arguments it works as intended, however when arguments are inserted manually it returns a number instead of a string and I can't identify why this is happening. It seems I did something wrong while printing the string with "printf ("The modified expression is: %s", s2);", since it never prints the intended string.
#include <stdio.h>
#include <math.h>
#include <string.h>
int nv(char *s1, char c1)
{
int i,count=0;
i=0;
if (s1 != NULL)
{
while(s1[i]!=0)
{
if (s1[i]==c1)
++count;
++i;
}
}
return count;
}
int po(char *s1, char c1)
{
int i;
i=0;
if (s1 != NULL)
{
while(s1[i]!=0)
{
if (s1[i]==c1)
return i;
++i;
}
}
return -1;
}
char *s(char *s1, char c1, char c2)
{
int i;
char expression[256];
char rep1[256];
char rep2[256];
if (s1 == NULL)
{
printf("No command line arguments! Please insert the expression to modify.\n");
scanf(" %s",expression);
s1=expression;
printf("Insert the character to replace.\n");
scanf(" %s",rep1);
c1=*rep1;
printf("Insert the replacement character.\n");
scanf(" %s",rep2);
c2=*rep2;
}
i=0;
if (s1 != NULL)
{
while(s1[i]!=0)
{
if (s1[i]==c1)
s1[i]=c2;
++i;
}
}
return s1;
}
int main(int argc, char *argv[])
{
int x,y,i = 0;
char *s1 = NULL,c1 = '\0',c2 = '\0';
char *s2 = NULL;
if(argc!=1)
{
x = nv(argv[1], argv[2][0]);
y = po(argv[1], argv[2][0]);
s1 = s(argv[1], argv[2][0], argv[3][0]);
printf("i=%d, count=%d, po=%d\n\n",i,x,y);
printf("\n %s \n\n", s1);
printf("\n\n");
}
else
{
x = nv(argv[1], argv[2][0]);
y = po(argv[1], argv[2][0]);
s2 = s(s1,c1,c2);
printf ("The modified expression is: %s", s2);
printf("\n\n");
}
return 0;
}
Related
I'm trying to creat a program that removes all occurences from a character that I choose from a certain string and also returs the number of characters that were removed.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define DIMV 10
int eliminar(char texto[], char ch, char novoTexto[]){
int a=0,i;
for(i=0; texto[i] != '\0';i++){
texto[i] = texto[i+a];
novoTexto[i]=texto[i];
if(novoTexto[i]==ch){
novoTexto[i] = '\0';
a++;
}
}
return a;
}
int main()
{
char frase[]="Uma arara torta!";
char res[50];
printf("%s\n",frase);
printf("%d\n",eliminar(frase,'r',res));
printf("%s\n",res);
return 0;
}
When I run the program, it returns:
Uma arara torta!
3
Uma a
What I wanted to return is:
Uma arara torta!
3
Uma aaa tota!
It's a silly question but I can't find the mistake that I made. Thank you!
Putting '\0' means to terminate the string there.
You have to skip adding characters to eliminate.
Try this:
int eliminar(char texto[], char ch, char novoTexto[]){
int a=0,i,j=0;
for(i=0; texto[i] != '\0';i++){
if(texto[i]==ch){
a++;
}else{
novoTexto[j]=texto[i];
j++;
}
}
novoTexto[j]='\0';
return a;
}
Putting '\0' means to terminate the string there.
check this:
int eliminator(char * texto, char ch, char * novoTexto) {
int i=0;
while(*texto != '\0') {
if (*texto == ch) {
texto++;
++i;
} else {
*novoTexto++ = *texto++;
}
}
*novoTexto = '\0';
return i;
}
int main(int arg, char **argv) {
char frase[] = "Uma arara torta!";
char res[50];
printf("%s\n",frase);
printf("%d\n",eliminator(frase, 'r', res));
printf("%s\n",res);
}
#include <stdio.h>
#include <string.h>
void separate(char s[20], char dummy[10], char* p){
strcpy(dummy, s);
for (int i = 0; i < strlen(dummy); i++){
if (dummy[i] == ' '){
dummy[i] = '\0';
}
}
*p = strchr(s, ' ');
p++;
}
int main(){
char s[10];
char dummy[10];
char l;
gets(s);
separate(s, dummy, &l);
puts(dummy);
puts(l);
}
I'm having trouble passing the last name to the main function as a string, the goal is to separate a string that consists of someone's first and last name.
#include <stdio.h>
#include <string.h>
void separate(char name[], char first[], char last[]){
strcpy(first, name);
for (int i = 0; i < strlen(first); i++){
if (first[i] == ' '){
first[i] = '\0';
}
}
char *p = strchr(name, ' ');
p++;
strcpy(last, p);
}
int main(){
char n[10], f[10], l[10];
gets(n);
separate(n, f, l);
puts(f);
puts(l);
}
I figured it out, thanks for the help anyway.
Here is an example of using fgets:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFSIZE 20
#define NAMESTRLEN 10
void separate(char buffer[], char firstname[], char lastname[]);
int
main(void) {
char buffer[BUFFSIZE], firstname[NAMESTRLEN], lastname[NAMESTRLEN];
size_t slen;
printf("Enter first and last name: ");
if (fgets(buffer, BUFFSIZE, stdin) == NULL) {
printf("Error reading into buffer.\n");
exit(EXIT_FAILURE);
}
slen = strlen(buffer);
if (slen > 0) {
if (buffer[slen-1] == '\n') {
buffer[slen-1] = '\0';
} else {
printf("Exceeded buffer length: %d.\n", BUFFSIZE);
exit(EXIT_FAILURE);
}
}
if (!*buffer) {
printf("Nothing entered.\n");
exit(EXIT_FAILURE);
}
separate(buffer, firstname, lastname);
printf("Firstname = %s\n", firstname);
printf("Lastname = %s\n", lastname);
return 0;
}
void
separate(char buffer[], char firstname[], char lastname[]) {
int i;
char *last;
const char sep = ' ';
for (i = 0; buffer[i] != sep; i++) {
firstname[i] = buffer[i];
}
firstname[i] = '\0';
last = strchr(buffer, sep);
last++;
strcpy(lastname, last);
}
I'm trying to write a code that goes through a given string using a pointer to parse it.
The original code I wrote worked fine but it was... redundant so I tried making it into a function call to make it more concise. Here is what i have:
char inputArray[300];
char buffer[300];
char username[100];
char password[100];
char name[100];
int i=0;
void repeat(char *to)
{
while(*to!='=')
{
to++;
}
}
void array(char *mm,char *tt)
{
i=0;
while(*tt!='+')
{
mm[i]=*tt;
tt++;
i++;
}
}
int main()
{
printf("give me the shit in this fashion: username=?+password=?+real=?\n");
scanf("%s",inputArray);
strcpy(buffer,inputArray);
char *tok=buffer;
repeat(tok);
tok++;
array(username,tok);
repeat(tok);
tok++;
array(password,tok);
tok++;
repeat(tok);
tok++;
array(name,tok);
}
For some reason it won't give me back the pointer array tok where it left off from the previous function call. why is that? it acts as if after calling it the pointer starts back from the beginning.
Functions receive copies of their arguments. Original arguments remain unaffected.
Giving something back has a special syntax in C: the return statement. Thus
char* repeat (char *to) // <- this function gives back a char*
{
while (*to != '=')
{
to++;
}
return to; // <- giving something back
}
Call it like this:
tok = repeat(tok);
Treat array in the same fashion.
Note 1, this function will result in *undefined behaviour if the string doesn't contain '='.
Note 2, it is also possible to pass a pointer to tok as the other answer suggests, but for sake of clarity it is only recommended to use this style when you need to return more than one thing from a function.
just change your repeat to this:
void repeat(char **to) {
while (**to != '=') {
(*to)++;
}
}
and call it like this:
repeat(&tok);
and always check for errors:
if (scanf("%299s", inputArray) != 1){
printf("incorrect input\n");
return 1;
}
and your sample code (and add check for errors in array and repeat to not go out of bounds):
#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
char inputArray[300];
char buffer[300];
char username[300];
char password[300];
char name[300];
int i = 0;
void repeat(char **to) {
while (**to != '=') {
(*to)++;
}
}
void array(char *mm, char *tt){
i = 0;
while (*tt != '+') {
mm[i] = *tt;
tt++;
i++;
}
}
int main() {
printf("give me the shit in this fashion: username=?+password=?+real=?\n");
if (scanf("%299s", inputArray) != 1){
printf("incorrect input\n");
return 1;
}
inputArray[299] = 0;
strcpy(buffer, inputArray);
char *tok = buffer;
repeat(&tok);
tok++;
array(username, tok);
repeat(&tok);
tok++;
array(password, tok);
tok++;
repeat(&tok);
tok++;
array(name, tok);
}
and you may use this to not go out of bounds:
#include <inttypes.h>
#include <stdio.h>
#include <stdint.h>
char* read_str(char *src, char *dst){
char *p, *q;
p = src;
while (*p != 0 && *p != '=') p++;
if (*p == 0) {
*dst = 0;
return NULL; // '=' not found
}
p++;
q = p;
while (*q != 0 && *q != '+') q++;
//if (*q == 0) return NULL;// '+' not found
while (p <= q) *dst++ = *p++;
dst--;
*dst = 0;
q++;
return q;
}
#define MAX_LEN 100
int main() {
char username[MAX_LEN];
char password[MAX_LEN];
char name[MAX_LEN];
char inputArray[MAX_LEN] = "username=Alex+password=123+real=Alex";
char *p = inputArray;
p = read_str(p, username);
if (p == NULL)return 1; // error
p = read_str(p, password);
if (p == NULL)return 1; // error
read_str(p, name);
printf("username: %s \n", username);
printf("password: %s \n", password);
printf(" name: %s \n", name);
}
I'm trying to get this code to work, but I have no idea how to restart the inner while loop. How would I do it?
/*
* Return a pointer to the first occurrence of any character in <stop>
* in the given <string> or NULL if the <string> contains no characters
* in <stop>.
*****
* YOU MAY *NOT* USE INTEGERS OR ARRAY INDEXING.
*****
*/
char *find_any_ptr(char *string, char* stop) {
char *newstring = (char*)0;
while(*stop != '\0'){
while(*string != '\0') {
if(*string == *stop){
if(newstring < string || newstring != (char*)0){
string++;
}else{
newstring = string;
string++;
}
}
}
stop++;
}
return newstring; // placeholder
}
Use a temporary variable for string pointer, and use this temp variable instead inside the inner loop.
while(*stop != '\0'){
char *p = string;
while (*p != '\0') {
... /* use 'p' in place of 'string' */
}
stop++;
}
This is relatively simple using nothing but a character pointer to the string and a pointer to stop. For each character in your string, you compare against each character in stop, returning the character in string on match, or NULL if no match is found:
#include <stdio.h>
char *find_any_index(char string[], char stop[]) {
char *p = string;
char *sp = NULL;
while (*p)
{
sp = stop;
while (*sp)
{
if (*sp == *p)
return p;
sp++;
}
p++;
}
return NULL;
}
int main (int argc, char **argv) {
if (argc < 3) {
printf ("usage: %s string stoplist\n", argv[0]);
}
printf ("\n string: %s\n stop : %s\n\n", argv[1], argv[2]);
printf (" first char in string matching a char in stop: %s\n\n", find_any_index (argv[1], argv[2]));
return 0;
}
Output
$ ./bin/find_substr_str thisIsAstring mase
string: thisIsAstring
stop : mase
first char in string matching a char in stop: sIsAstring
Here is a demonstrative program that shows how the function can be written
#include <stdio.h>
char * find_any_ptr( const char *string, const char* stop )
{
const char *p, *q;
_Bool found = 0;
p = string;
do
{
q = stop;
while ( *q && *q != *p ) ++q;
} while ( !( found = *q ) && *++p );
return ( char * )( found ? p : NULL );
}
int main(void)
{
const char *p = find_any_ptr( "abc9de", "1234567890" );
if ( p ) puts( p );
return 0;
}
The program output is
9de
Only I would name the function find_any_char instead of find_any_ptr:)
This is my implementation:
#include <stdio.h>
#include <stdlib.h>
char * findany(char *string, char *stop) {
char * app;
//To avoid segmentation fault!
if (stop==NULL || string==NULL || !*stop || !*string)
return NULL;
do {
app=string;
while(*app!=0 && *app!=*stop)
app++;
stop++;
} while(*app==0 && *stop!=0);
return (*app!=0)?app:NULL;
}
int main(void)
{
char string[100];
char stop[100];
char * found;
for(;;) {
printf("Insert a string without spaces[q<Enter> to exit]: ");
scanf("%s",string);
if (!strcmp(string,"q"))
break;
printf("Insert the chars to search without spaces: ");
scanf("%s",stop);
printf("Searching any occurence of a char in \"%s\""
" inside \"%s\"\n",stop,string);
found=findany(string,stop);
printf("%s\n",(found!=NULL)?found:"NULL");
}
return 0;
}
I think that is better to use also the following way to implement the function findany():
char * _findany(char *string, char *stop) {
char * app; // to start the first loop
//To avoid segmentation fault!
if (stop==NULL || string==NULL || !*stop || !*string)
return NULL;
do {
app=stop;
while(*app!=0 && *app!=*string)
app++;
string++;
} while(*app==0 && *string!=0);
return (*app!=0)?(string-1):NULL;
}
You may observe the difference between the two functions adding the function _findany in the code above and to call the new function adding the following code after (or before) the printf in the main above.
found=_findany(string,stop);
printf("%s\n",(found!=NULL)?found:"NULL");
I wrote the below code which replaces '|' characters from the string.
#include <stdio.h>
#include <stdlib.h>
void remove_pipes(char*);
main (int argc, char **argv)
{
char string1[] = "|||||||||||||";
remove_pipes(string1);
printf("String1 = %s", string1);
char string2[] = "h|e|l|l|o";
remove_pipes(string2);
printf("String2 = %s", string2);
}
void remove_pipes(char* input)
{
for(; *input; input++)
{
if(*input == '|')
{
*input = ' ';
}
}
}
Now I need to modify this method to remove the '|' character from the string. I am not sure how to do that. Hope someone can give me some hint.
Use a char pointer to travel the input and modify it:
#include <stdio.h>
#include <stdlib.h>
void remove_pipes(char*);
main (int argc, char **argv)
{
char string1[] = "|||||||||||||";
printf("String1 = %s\n", string1);
remove_pipes(string1);
printf("String1 = %s\n", string1);
char string2[] = "h|e|l|l|o";
printf("String2 = %s\n", string2);
remove_pipes(string2);
printf("String2 = %s\n", string2);
}
void remove_pipes(char* input)
{
unsigned idx = 0;
char* aux = input;
for(; *input; input++)
{
if (*input != '|')
{
*(aux + idx++) = *input;
}
}
*(aux + idx) = '\0';
}