Want this program will be output "Digi" but why it's output "Dig)tal Bangladesh".
Can anyone explain?
#include<stdio.h>
int main(){
char str[120]="Digital Bangladesh";
int n;
n=strlen(str);
printf("%d \n",n);
str[4]="\0";
printf("%s",str);
return 0;
}
I have given basic explanation in the comments and improved your code a little (replaced "\0" with '\0' and included string.h for strlen()).
#include <stdio.h>
#include <string.h>
int main() {
char str[120] = "Digital Bangladesh";
int n = strlen(str); // can combine declaration and assignment into a single statement;
// this will assign the actual length of string str to n
printf("%d \n", n);
str[4] = '\0'; // shouldn't be "\0" since anything in double quotes will be a string and not a character
// you are assigning 5th character (4th index + 1) of str to NULL ('\0') terminator character;
// now str will have content "Digi"
printf("%s", str);
return 0;
}
Related
I'm just getting started with C and I just started trying to figure out
call by reference in functions. I have noticed an odd result in my output
when using strlen() to iterate over a string and modify its contents. In this
example the result of strlen() is 3, not including the null character,
but if I do not explicitly check for the null character (or use less than the
result of strlen() instead of less than or equals) during the for loop then
it gives a bizarre bit character in the output which I ASSUME is because of the null character?
Please help this noob to understand what is happening here.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void f_test_s(char s[]);
void f_test_s2(char s[]);
int main(){
char s_test[] = "abc";
f_test_s(s_test);
f_test_s2(s_test);
puts("\nTest complete!");
return 0;
}
void f_test_s(char s[]){
puts("Test #1: ");
printf("string before: %s\n", s);
int len = strlen(s);
printf("strlen() = %d\n", len);
int i=0;
for(i=0;i<=len;i++){
if(s[i] != '\0'){
s[i]++;
}
}
printf("string after: %s\n", s);
}
void f_test_s2(char s[]){
puts("\nTest #2: ");
printf("string before: %s\n", s);
int len = strlen(s);
printf("strlen() = %d\n", len);
int i=0;
for(i=0;i<=len;i++){
s[i]++;
}
printf("string after: %s\n", s);
}
output:
Test #1:
string before: abc
strlen() = 3
string after: bcd
Test #2:
string before: bcd
strlen() = 3
string after: cde
Test complete!
If it matters I am using gcc version 7.3.0 on Ubuntu. I am definitely
not an expert with either C, gcc, or Ubuntu.
This is the problem:
for (i = 0; i <= len; i++) {
s[i]++;
}
It should be:
for (i = 0; i < len; i++) {
s[i]++;
}
s[len] is the null char (0). When you removed null char and replaced it with the value of 1, the contents of the array are now {'a', 'b', 'c', 0x1}. And when printf attempts to print s it's going to keep printing characters past the value memory address of the array until it encounters a null char. Technically this is undefined behavior.
Change this:
for (i = 0; i <= len; i++) {
to this:
for (i = 0; i < len; i++) {
since strlen() returns the length of the string. A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
Your code invokes Undefined Behavior (UB), since you go out of bounds. Standard string functions (like printf()) depend on the NULL terminating character to mark the end of the string. Without it, they do not know when to stop . . .
I'm trying to find to find which position a number has in a sentence in c. I'm kinda new to programming and i don't know why my code isn't working.
i keep getting this warning but i have no clue what it means (english isn't my first language):
passing argument 1 of 'strcmp' makes pointer from integer without a cast [-Wint-conversion] Main.c /TweeIntegers line 20 C/C++ Problem
My code:
#include <stdio.h>
#include <string.h>
int main()
{
int i, y;
char x;
char text1[] = "een stuk text";
char text2[] = "k";
for ( i = 0; i < strlen(text1); i++ )
{
x = text1[i];
y = strcmp( x, text2 )
}
printf("%d", i);
return 0;
}
strcspn will search for list of characters and return the index of the first match. In this case the list is only the letter k. In case of no match found it returns the length of the string searched.
#include <stdio.h>
#include <string.h>
int main()
{
int y = 0;
char text1[] = "een stuk text";
char text2[] = "k";
y = strcspn ( text1, text2);
printf("%d", y);
return 0;
}
if you are only looking for a char and the first position then you can use the following code:
#include <stdio.h>
#include <string.h>
int main()
{
int i;
char text1[] = "een stuk text";
char charYouLookFor = 'k';
for ( i = 0; i < strlen(text1); i++ )
{
if (text1[i] == charYouLookFor)
break;
}
printf("%d", i);
return 0;
}
If you are looking for the position of a text in a text or for the second position of the char the code needs to be more complex.
You are trying to compare a single character with a string, but strcmp() compares two strings. You can solve this by dropping the whole loop and simply use strchr() to locate the character. strstr(text1, text2) would have worked as well, since text2 is a string (properly null-terminated).
Pre-made search functions in string.h:
strchr() finds a single character inside a string.
strstr() finds a sub-string inside another string.
strpbrk() finds any character from a list of specified characters inside another string.
You can only use strcmp() to compare whole strings, which is not what you're trying to do.
To locate a single character in a string, just use strchr(). No need to loop yourself:
#include <stdio.h>
#include <string.h>
int main()
{
int i, y;
char x;
const char text[] = "een stuk text";
char letter = 'k';
const char * const found = strchr(text, letter);
if(found != 0)
printf("%d\n", (int) (found - text));
return 0;
}
This prints:
7
Which is correct, it's the 8th letter.
The program stops working.
Even if I put only one int.
I tried many different ways but can't figure out what is wrong.
I am trying to take input of integers separated by space.
There can be any no of integers.
#include<stdio.h>
#include<stdlib.h>
int main(void) {
int i,j=0;
int b[100];
char a[100];
fgets(a,100,stdin);
for(i=0;i<strlen(a);i++)
{
b[i] = atoi(a[j]);
j=j+2;
}
for(i=0;i<strlen(b);i++)
{
printf("%d ",b[i]);
}
}
Here is the prototype of atoi you have to use a character array but you are sending a character only.atoi(str[i])
int atoi(const char *str)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int val;
char str[20];
strcpy(str, "98993489");
val = atoi(str);
printf("String value = %s, Int value = %d\n", str, val);
return(0);
}
Do the following:
for(i = 0; i < strlen(a); i += 2)
{
b[j] = a[i];
j++;
}
though atoi() accepts only a string argument or u can say constant char pointer and str[i] is nothing but a pointer pointing at a single character of the character array.
Therefore once we pass atoi(str[i]) , that means we are passing a character to the function, which will give an error.
Therefore you must pass the address of that particular character from where you want to convert the substring into a number i.e. atoi(&str[i]).
I have I problem. I get 2 warnings from console, but I dont know what's wrong with my code. Can you have look?
Program suppose to show lines with at least 11 characters and 4 numbers
#include <stdio.h>
#include <ctype.h>
int main()
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
if(isalpha(line)) numberAlpha++;
else if(isdigit(line)) numberDigit++;
if(numberAlpha+numberDigit>10 && numberDigit>3) printf("%s \n", line);
}
return 0;
}
Both isalpha() and isdigit() takes an int, not a char *, as argument.
In your code, by passing the array name as the argument, you're essentially passing a char * (array name decays to the pointer to the first element when used as function argument), so, you're getting the warning.
You need to loop over the individual elements of line and pass them to the functions.
That said, just a suggestion, for hosted environment, int main() should be int main(void) to conform to the standard.
isalpha and isdigit are supposed to test if a char taken as int (a char can be safely converted to an int) is the encoding of an alphanumeric or digit character. You pass a char array, not an individual char. You need to test each char of the string you got, so you need a loop as:
for (int i=0; i<strlen(line); i++) {
if (isalpha(line[i])) numberAlpha++;
...
}
It is better to compute the length once:
int length = strlen(line);
for (int i=0; i<length; i++) {
...
}
You may also use a pointer to move along the string:
for (char *ptr = line; *ptr!=`\0`; ptr++) {
if (isalpha(*ptr)) ...
...
}
isalpha() and isdigit() functions take an int. But you are passing a char* i.e. the array line gets converted into a pointer to its first element (see: What is array decaying?). That's what the compiler complains about. You need to loop over line to find the number of digits and alphabets in it.
Also note that fgets() will read in the newline character if line has space. So, you need to trim it out before counting.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
line[strcspn(line, "\n")] = 0; // Remove the trailing newline, if any.
for (size_t i = 0; line[i]; i++) {
if(isalpha((unsigned char)line[i])) numberAlpha++;
else if((unsigned char)isdigit(line[i])) numberDigit++;
}
printf("alpha: %d, digits:%d \n", numberAlpha, numberDigit);
}
return 0;
}
Ok, i got something like this:
#include <stdio.h>
#include <ctype.h>
int main()
{
char line[200];
printf("Enter a string: \n");
while(fgets(line, sizeof(line),stdin))
{
int numberAlpha = 0;
int numberDigit = 0;
int i;
for(i=0; i<strlen(line); i++){
if(isalpha(line[i])) numberAlpha++;
else if(isdigit(line[i])) numberDigit++;
}
if(numberAlpha+numberDigit>10 && numberDigit>3) printf("%s \n", line);
}
return 0;
}
Now the question is, if it is passible to make it first accepts data and then display only those line which follows the if statment. Now it shows line just after input it.
So after a few years of inactivity after studying at uni, I'm trying to build up my c experience with a simple string reverser.
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
*
*/
int main(int argc, char** argv) {
reverser();
return(0);
}
int reverser(){
printf("Please enter a String: ");
//return (0);
int len;
char input[10];
scanf("%s",&input);
int quit = strcmp(input,"quit");
if(quit == 0){
printf("%s\n","Program quitting");
return(0);
}
len = strlen(input);
printf("%i\n",len);
char reversed[len];
int count = 0;
while (count <= (len-1)){
//printf("%i\n",(len-count));
reversed[count] = input[(len-1)-count];
count++;
}
//printf("%s\n",input);
printf(reversed);
printf("\n");
reverser();
}
When I input "hello", you would expect "olleh" as the response, but I get "olleh:$a ca&#",
How do I just get the string input reversed and returned?
Bombalur
Add a '\0' at the end of the array. (as in, copy only chars until you reach '\0' - which is the point at array[strlen(array)], then when you're done, add a '\0' at the next character)
Strings are conventionally terminated by a zero byte. So it should be
char reversed[len+1];
And you should clear the last byte
reversed[len] = (char)0;
you forgot the \0 at the end of the string
This is because you are creating an array with size 10. When you take in some data into it (using scanf) and the array is not filled up completely, the printf from this array will give junk values in the memory. You should iterate for the length of the input by checking \n.
must have a size + 1 to string length so that you can have a \0 at the end of string that will solve your problem
The following is a (simple and minimal implementation of) string reverse program (obviously, error conditions, corner cases, blank spaces, wider character sets, etc has not been considered).
#include <stdio.h>
int strlen(char *s)
{
char *p = s;
while (*p)
p++;
return p - s;
}
char * strrev(char a[])
{
int i, j;
char temp;
for (i=0, j=strlen(a)-1 ; i<j ; i++, j--) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a;
}
int main()
{
char str[100];
printf("Enter string: ");
scanf("%s", str);
printf("The reverse is %s \n", strrev(str));
return 0;
}
Hope this helps!