I'm new to coding and I've been studying C recently. Basically, I wanted to create the following function, which modifies every string element:
char *stralt(char *s, char ch)
{
int i;
for (i=0; i!='\0'; i++)
s[i] = ch;
return s;
}
And when I try to use it on int main(), like this:
int main()
{
printf("%s", stralt("test",'x'));
}
The prompt shows "test" instead of "xxxx". What is wrong with this code and how could it work properly?
Thanks!
You have two problems, one of which isn't apparent because the other doesn't allow it to occur.
You have:
for (i = 0; i != '\0'; i++)
Here, you compare the value of i against '\0', which is 0. Since i is 0 at the beginning of the for loop, the condition i != '\0' will be false, and the loop will exit before entering the body.
It seems that you meant to say:
for (i = 0; s[i] != '\0'; i++)
The other problem is that you're trying to modify a string literal. s[i] = ch; is invalid if s points to a string literal, as it does in your example.
Instead, you have to have a modifiable array of characters. This could be accomplished by modifying your main like:
int main()
{
char test_str[] = "test";
printf("%s", stralt(test_str, 'x'));
}
Related
#include <stdio.h>
int strcompare (char*);
int main (int argc, char *argv[])
{
int argIndex;
for(argIndex = 1; argIndex <= argc; argIndex++)
{
strcompare(argv[argIndex]);
printf("%s has %d letters in it\n", argv[argIndex], strcompare(argv[argIndex]));
}
return 0;
}
int strcompare (char *str)
{
int index, letterDex = 0;
for (index = 0; *str != '0'; index++)
{
letterDex++;
}
}
The assignment is to count the number of letters in a word, when I compile I don't get any errors, but when I try to run it it just doesn't work at all
./cma_length noah bruh conner
and nothing comes after it when I hit enter.
Four problems:
missing the return statement on your strcompare
youwasn't updating the pointer of the char*
in C array that have 4 element, has the last element in index 3, so in the for loop condition, you have to check for<, not for <=
*str != '0' is wrong, you are checking if the char is the char 0, not the escape char, which is \0 so check for this char in this way *str != '\0'
With those things done, the code will be this:
#include <stdio.h>
int strcompare (char*);
int main (int argc, char *argv[])
{
int argIndex;
for(argIndex = 1; argIndex < argc; argIndex++){
strcompare(argv[argIndex]);
printf("%s has %d letters in it\n", argv[argIndex], strcompare(argv[argIndex]));
}
return 0;
}
int strcompare (char *str){
int letterDex;
for (letterDex = 1; *str != '\0'; letterDex++){
str++;
}
return letterDex;
}
Also the index variable was useless, so i've just removed it
It doesn't look like code which compiles. The function strcompare should return an int and in the implementation above it doesn't return anything. I assume there's a return letterDex; at the end of your function but you lost it when copying the code here.
In the for loop in the strcompare function you're comparing the *str to '0'. Now there are two things that are wrong here I think:
You're comparing *str to '0' but you don't change the pointer value. So you're comparing the first character to '0' all the time. You should either do str[index] != '0' or instead of using index increment the pointer.
I think that you want to look for a '\0' instead of '0'. The '\0' is a null terminator character meaning the end of the string.
The reason why you're not seeing anything happening is because you're stuck in an infinite loop.
**i am trying to reverse a string so what i am trying is to take the string to its last position and from there i am storing it to a new character array and printing that but not getting desired output **
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char c[10];
printf("Enter the string:\n");
gets(c);
rev(c);
return 0;
}
void rev(char c[])
{
int i = 0,j = 0;
char s[10];
while(c[j] ! = '\0')//reaching to end of string
{
j++;
}
while(s[i] ! = '\0')
{
s[i] = c[j];//copying string c from end into string s from begining
i++;
j--;
}
s[i+1]='\0';
printf("The string after reverse: %s",s);//printing reversed string
}
while(s[i] ! = '\0')
In above line s[i] is uninitialized and hence you are invoking undefined behaviour by accessing uninitialized value and thus incorrect result.
To fix this, you can rewrite the condition as:
while(j >= 0)
Apart from these, for sane result, you need following two changes:
The final termination should be re-written as:
s[i]='\0';
The initial value of j should be decremented by 1. (As c[j] would point to the null character)
as i is now already pointing past the size of c string.
problem is when you use gets() the buffer is usually dirty. I would suggest you use fflush(stdin) before the gets().
Also the last line where you say s[i+1] = '\0' should be s[i] = '\0' the i already was incremented by one after the last execution of the loop.
And as said above it shouldnt be while (s[i] != '\0')
s is not initialized so God knows whats in there. make it like while ( j >=0) and it should work.
why following code is giving garbage value ?
here I am trying to get an string as an input from user character by character. In the following code i have got input from user and stored in string[] array then in order to do some other operations i have stored the same in other array called temp_string[i]. But surprisingly i am getting garbage value in output.and also length calculated using strlen is not correct. can anybody look at this code and explain whats going wrong?
#include<stdio.h>
#include<stdio.h>
int main()
{
char ch;
int i = 0, j = 0;
int length = 0;
int lengthsb = 0;
char string[100];
printf(" Enter the string to divide\n ");
while(ch != '\n')
{
ch = getchar();
string[i] = ch;
i++;
}
char temp_string[i];
printf("%s", string);
i = 0;
while(string[i] != '\n')
{
temp_string[i] = string[i];
i++;
}
length = strlen(temp_string);
printf("Entered string is %s and its length is %d\n", temp_string, length);
}
You forgot to add the null at the end of the string.
C strings are null-terminated, that means that all operations in c strings expect a null to mark the end of the string, including functions like strlen.
you can achieve that just adding:
string[i] = '\0';
After fill the string.
Another thing, what happens if the user enters a string bigger than 100? Is good to validate the input for these cases, otherwise you can get a buffer overflow.
You need to add a NULL - terminated at the end of your string. Add \0.
You need to put a '\0' char at the end of the string so strlen(), printf() and other C functions dealing with strings will work. That is how the C API knows it reached the end of the string.
Also, you don't want to set new characters at the memory space past the string array. So you better check that in your loop (and save a last array item to set the '\0').
while (ch != '\n' && i < 99)
{
ch = getchar();
string[i] = ch;
i++;
}
string[i] = '\0'; // set the string terminator past the end of the input
Remember to do the same after copying the characters to temp_string. (By the way, you can replace that loop with a call to strcpy(), that does exactly that, except it will end only when it finds a '\0'.)
You might also want to read What's the rationale for null terminated strings?
Here is your Final Code:
#include<stdio.h>
#include<stdio.h>
#include<string.h>
int main()
{
char ch;
int i = 0, j = 0;
int length = 0;
int lengthsb = 0;
char string[100];
char temp_string[100];
printf(" Enter the string to divide\n ");
while(ch != '\n')
{
ch = getchar();
string[i] = ch;
i++;
}
string[i]=NULL;
printf("%s", string);
i = 0;
while(string[i] != '\0')
{
temp_string[i] = string[i];
i++;
}
temp_string[i]=NULL;
length = strlen(temp_string);
printf("Entered string is %s and its length is %d\n", temp_string, length);
}
In the above code what exactly you are missing is NULL or '\0' termination of the string. I just added it to make it useful.
I have written a C program. It's a character counting program. I will give input as below
Input: ABCAPPPRC
And need as output: A2B1C2P3R1.
But it gives output as A2B1C2A1P3P2P1R1C1. It basically doing as per the logic I have written in program. But I don't want to count the characters of string which have already been counted. Can you suggest what logic I should implement for this?
#include <stdio.h>
int main()
{
char str[30]= "ABCAPPPRC";
char strOutPut[60]="";
char *ptr= &str, *ptr2=&str;
char ch='A';
int count=0;
puts(str);
while (*ptr !=NULL)
{
count =0;
ch = *ptr;
while (*ptr2!= NULL)
{
if (*ptr2 == ch) count++;
ptr2++;
}
printf("%c%d",*ptr, count);
ptr++;
ptr2 = ptr;
}
}
You need to separate the counting from the printing.
The first loop goes through the input and counts the number of occurrences of each character, storing the counts in an array indexed by the character code.
The second loop goes through the array of counts and prints the character corresponding to a non-zero count followed by that count.
For example:
#include <stdio.h>
int main(void)
{
char str[] = "ABCAPPPRC";
int counts[256] = { 0 };
puts(str);
for (char *ptr = str; *ptr != '\0'; ptr++)
counts[(unsigned char)*ptr]++;
for (int i = 0; i < 256; i++)
{
if (counts[i] != 0)
printf("%c%d", i, counts[i]);
}
putchar('\n');
return(0);
}
Sample output:
ABCAPPPRC
A2B1C2P3R1
I could not understand the first for loop. Could you please explain it?
The for control line steps through the string str one character at a time. It is the for loop equivalent of the outer while loop in your original code.
char *ptr = str;
...
while (*ptr != '\0')
{
...
ptr++;
}
The body of the loop converts *ptr (a plain char) into an unsigned char (so that it is guaranteed to be positive), and then uses that value as an index into the array counts. Thus, for example, on the first iteration, A is mapped to 65, and counts[65] is incremented. Thus, for each character code, the loop increments the count corresponding to that character code each time the character is encountered in the string.
The second loop then picks out the non-zero counts, printing the character code as a character followed by its count.
(Incidentally, you should have been getting a compilation warning from the original char *ptr = &str about a type mismatch between char * and char (*)[30]. Learn when to put ampersands in front of array names — you seldom do it unless there is also a subscript after the array name. Thus, &array is usually — but not always — wrong; by contrast, &array[0] is very often valid. Also note that on some machines, NULL is defined as ((void *)0) and this elicits a warning when you compare it to a plain char, as you did with while (*ptr != NULL). You should compare characters to '\0' as in my rewrite; you should reserve NULL for use with pointers.)
str is alerady a character pointer, so when you do this: char *ptr= &str you convert a pointer to pointer to character to a char*. Loose the ampersand(&).
Also in the inner cycle you should check if the given value of ch has already been processed. In the case you use when ptr is pointing to the second A you should just continue, because you have already added the number of A-s in the answer.
Your solution is far from optimal. I strongly suggest you lookup counting sort. It will make your solution faster but also will make it simpler.
# Jonathan your solution is correct only when string characters are given in ascending order like ABCDEF, but it gives problem when character order is changed. Input string is "ABAPPPRCC" and required output is A2B1P3R1C2.
Here in this case your solution will change out put to A2B1C2P3R1.
Below program gives character count without changing string formation.
char *str= "ABAPPPRCC";
char strOutPut[30]="";
char *ptr = str, *ptr2 = str;
char ch='A';
int count=0, i = 0 , total_print = 0;
puts(str);
while (*ptr != '\0')
{
count =0;
ch = *ptr;
while (*ptr2!= '\0')
{
if (*ptr2 == ch) count++;
ptr2++;
}
for( i = 0; i < total_print ; i++ )
{
if ( ch == strOutPut[i] )
{
i = total_print + 1;
break;
}
}
if( i <= total_print )
{
printf("%c%d",*ptr, count);
strOutPut[total_print++] = ch;
}
ptr++;
ptr2 = ptr;
}
#include <stdio.h>
int main(void){
const char noncountchar = '\x11';
char str[30]= "ABCAPPPRC";
char strOutPut[60]="";
char *ptr, *ptr2;
char ch;
int count=0, len=0;
puts(str);
for(ptr=str;ch=*ptr;++ptr){
if(ch == noncountchar) continue;
count =1;
for(ptr2=ptr+1;*ptr2;++ptr2){
if (*ptr2 == ch){
*ptr2 = noncountchar;
++count;
}
}
len += sprintf(strOutPut+len, "%c%d", *ptr, count);
}
printf("%s", strOutPut);
return 0;
}
I have a problem in C where i have to find number of occurrence of each character in a string.Suppose i have string like "amitamt" and output should be like "a2m2it2" .I have a routine from which i can find no of occurrence of a particular character.
int count_chars(const char* string, char ch)
{
int count = 0;
int i;
int length = strlen(string);
for (i = 0; i < length; i++)
{
if (string[i] == ch)
{
count++;
}
}
return count;
}
But I am not sure how could I count each character of string
If you have an ASCII string, create an int array of size 256. Then loop through the string and increment the value in the int array on position x. While x is the ASCII value of the character in your string you're looping through.
if i have any mistakes like syntax please excuse as im working on vb , Im unable to figure out where to put braces or brackets ,
and I belive strchr makes your task easier
#include <stdio.h>
#include <string.h>
int str_occ (char *pch ,char a)
{
int i = 0;
char *p;
p=strchr(pch,a);
while (p!=NULL)
{
i = i+1;
p = strchr(p+1,a);
}
return i;
}
To explain the code *pch is the string you have to pass ,char a is the alphabet you are searching to find how many times its occurring and int i returns the value of number of occurrences
say sample
int main()
{
char a[]="hello world";
int i;
i=str_occ(a,'l');
printf("%d",i);
}
output is 3
You can make the code as per your requirements, keep caling the function inside a loop , I mean rotate your elements