when I use strcmp:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *i, *j;
scanf("%s %s", &i, &j);
if (strcmp(i, j) == 0){
printf("Same \n");
} else {
printf("different\n");
}
}
output: gives no output just blank
When I directly compare i & j
#include <stdio.h>
#include <string.h>
int main(void)
{
char *i, *j;
scanf("%s %s", &i, &j);
if (i == j) {
printf("Same \n");
} else {
printf("different\n");
}
}
output : Same
Ye that's all I tried by replacing i == j with strcmp().
The problem is not related to the use of strcmp, you have undefined behavior in the way you use scanf() to read strings. You pass the addresses of string pointers where scanf() expects addresses of char arrays.
In both cases, the behavior is undefined and indeed the first program causes a segmentation fault, whereas the second seems to produce expected behavior, only by chance because the entered strings are short. Try longer strings and you might get a segmentation fault as well.
Here is a modified version with defined behavior:
#include <stdio.h>
#include <string.h>
int main(void) {
char i[100], j[100];
if (scanf("%99s %99s", i, j) == 2) {
if (strcmp(i, j) == 0) {
printf("Same\n");
} else {
printf("Different\n");
}
}
return 0;
}
Note how %99s tells scanf() to store at most 99 bytes into the destination arrays to avoid buffer overflows.
Also note how scanf return value must be tested to avoid accessing uninitialized data (it returns the number of successful conversions, which must be 2 for both i and j to contain valid C strings).
I replaced the *i and *j with i[50] and j[50] respectively.
And here I avoided using &i as in case of a string (character array), the variable itself points to the first element of the array in question. Thus, there is no need to use the ‘&’ operator to pass the address.
And now this would work with strcmp
#include<stdio.h>
#include<string.h>
int main(void){
char i[50], j[50];
printf("Enter strings: ");
scanf("%s %s", i, j);
if (strcmp(i, j) == 0) printf("Same \n");
else printf("different\n");
}
input:
Enter strings: hello(enter)
hello
output: same
Related
I'm in the middle of homework and nearly finish. This is my code
#include <stdio.h>
#include <stdlib.h>
void main()
{
char word[100],*ptr,input;
int count,i,n;
printf("Enter the word : ");
scanf("%[^\n]", word);
ptr = &word;
do
{
printf("Enter the letter : ");
scanf(" %c", &input);
if(input == '-'){
printf("Exit.");
return 0;
}
for(i=0;word[i] != '\0';i++)
{
if(*ptr == input)
count++;
ptr++;
}
printf("Has %d of '%c'",count,input);
printf("\n");
}while(input != '-')
}
This code will extract the number of letter in string
For example : If you input "WWWWooo" it will give you "has 4 of 'W'" and "has 3 of 'o'"
Code will exit when you put '-' letter.
Problem that I find is the 'count' value seems to remain the total of number of the first letter I want to find.
What I expect : "WWWWooo" will give "has 4 of 'W'" and "has 3 of 'o'"
What I get is "has 4 of 'W'" and "has 4 of 'o'". The count value didn't reset.
I tried to put count = 0; on the top of do while loop and the output will always be 0 for the second letter scanned for.
How can I fix this?
I changed your code a bit, I guess this is what you're looking for (the comments in the code explain pretty much all the changes I've made):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char word[100],*ptr,input;
int count,i,n;
printf("Enter the word : ");
scanf("%99[^\n]", word); //changed to %99[^\n] to avoid buffer overflows
do
{
count=0; //count=0 should be here as count++ changes the value of count afterwards
ptr=word; //ptr=word should be here too since ptr++ changes the value of ptr afterwards
/* you might have probably gotten a compiler warning because
of ptr=&word, since &word is char(*)[100] (a pointer to an array of 100 chars)
and char(*)[100] and char * are quite different,
so you can either do ptr=word or ptr=&word[0] (both of which point to the first character in the array) */
//the rest of the code below is basically the same
printf("Enter the letter : ");
scanf(" %c", &input);
if(input == '-'){
printf("Exit.");
return 0;
}
for(i=0;word[i] != '\0';i++)
{
if(*ptr == input)
count++;
ptr++;
}
printf("Has %d of '%c'",count,input);
printf("\n");
}while(input != '-'); //you had missed a ';' here
}
The int main(void) is because, quoting n1570 (emphasis mine):
It shall be defined with a return type of int and with no parameters:
int main(void) { /* ... */ } or with two parameters (referred to here
as argc and argv, though any names may be used, as they are local to
the function in which they are declared): int main(int argc, char
*argv[]) { /* ... */ } or equivalent
Even though I haven't checked the return value of scanf() in the above code, but as mentioned by #Yunnosch in the comment, it's always a good idea to do so.
I'm trying to make a program that will count how many letters occur in my string. I want only to count letters A and B on a give string.
char string[10];
int countA, countB;
gets(string);
for(int i = 0; i <strlen(string); i++){
if(string[i] == 'A')
countA++;
else if(string[i] == 'B')
countB++;
}
printf("%d %d", countA, countB);
return 0;
for example my input is: ABABA
the output should be 3 2 however it print a different answer for countB. I'm using devc++. Is this a bug?
Reason for getting different result:
Earlier when you didn't initialize the variable countA and countB they contained indeterminate value. Using them in your code introduces undefined behavior.
Two points:
Intialize the variables to zero. countA and countB.
And don't use gets rather use fgets.
I am giving you an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main(){
char string[10];
unsigned int countA=0, countB=0;
if( fgets(string,10,stdin) == NULL){
fprintf(stderr, "%s\n", "Error in string input");
exit(1);
}
size_t len = strlen(string);
if( len > 0 )
string[len-1]='\0';
for(size_t i = 0; i <strlen(string); i++){
if(string[i] == 'A'){
countA++;
}
else if(string[i] == 'B'){
countB++;
}
}
printf("%u %u", countA, countB);
return EXIT_SUCCESS;
}
Note:
Also you are asked whether it is gloabal variable. If it was then probably you wouldn't have to worry about initialization. They would be initialized with 0.
gets() goes on reading characters until it encounters \n or EOF. And on doing this it is not constrained in anyway with the buffer size, leaving a chance of buffer overflow.
If I give input 'hello' for variable s and a for variable i cant able to give input
#include<stdio.h>
#include<string.h>
int main(){
char s[100],a,b;
//i am not able to get this value,please help me how to get three variables s,a,b at runtime
scanf("%c",s);
scanf("%c",a);
scanf("%c",b);
int n=strlen(s),count=0;
for(int i=0;i<n;i++){
if(s[i]==a && s[i+1]== b)
count++;
}
printf("%d",count);
return 0;
}
First of all try to use scanf("%c",&a) scanf.
Then read the three variables using just one scanf.
Try this program it will resolve your problem:
#include <stdio.h>
#include <string.h>
int main()
{
char s[100], a, b;
//i am not able to get this value,please help me how to get three variables s,a,b at runtime
scanf("%s %c %c", s, &a, &b);
int n = strlen(s), count = 0;
for(int i = 0; i < (n - 1); i++){
if(s[i] == a && s[i+1] == b)
count++;
}
printf("%d",count);
return 0;
}
When scanning character, use white space before character modifier, and pass char as pointer, not as value. For scanning entire string, use modified %s. In this case, you don't need to write &s as s itself is already contain memory address of array. If you still want to use & infront, then use &s[0] because &s[0] == s.
char s[100], a, b;
scanf("%s", s);
scanf(" %c", &a);
scanf(" %c", &b);
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 am having trouble storing strings into a 2d array using scanf.
To illustrate, this is the input the program accepts:
p2/src/stuff:5:
p3/src/stuff:5:
p4/src/stuff:6:
So I want to be able to split the strings and numbers by colons and store them separately. So ideally, my 2d array would look like this for strings:
[["p2/src/stuff"], ["p3/src/stuff"], ["p4/src/stuff"]]
Numbers can be stored in a 1d array.
Here is what I have so far:
int main() {
char *str;
char *i;
int n = 1;
while (n == 1) {
n = scanf("%m[^':']:%m[^':']:", &str, &i);
}
printf("# inputs read: %d\n", n);
printf("%s\n", str);
printf("%s\n", i);
}
Here it only prints the first line:
p2/src/stuff
5
Should I have an iterator that dose pointer arithmetic? I'm not familiar with pointer arithmetic.
scanf returns the number of items scanned. In this case it would be 2 instead of 1. Here a return of 1 would indicate a problem during the scan.
The %m specifier allocates memory to the pointers. Using a single pair of pointers, they should be freed in eadh iteration of the loop. You could use an array of pointers to store each of the inputs.
The scanset does not need the single quotes [^':']. If you are scanning for all characters that are not a colon [^:] will work.
EOF will terminate the while loop so if you are reading from a file, it will stop at the end of the file. Reading from stdin could be terminated using Ctrl+D (Linux) or Ctrl+Z (Windows).
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *str;
char *i;
int n;
while ( ( n = scanf("%m[^:]:%m[^:]:", &str, &i)) == 2) {
printf("# inputs read: %d\n", n);
printf("%s\n", str);
printf("%s\n", i);
free ( str);
free ( i);
}
return 0;
}
EDIT:
This uses an array of pointers to collect several inputs to the str and i arrays.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char *str[10];// array of pointers
char *i[10];
int each = 0;
int loop = 0;
int n = 0;
while ( ( n = scanf("%m[^:]:%m[^:]:", &str[each], &i[each])) == 2) {
printf("# inputs read: %d\n", n);
printf("%s\n", str[each]);
printf("%s\n", i[each]);
each++;
if ( each > 9) {
break;//too many inputs for array size
}
}
for ( loop = 0; loop < each; loop++) {
printf ( "str[%d]=%s\n", loop, str[loop]);//print all the str inputs
}
for ( loop = 0; loop < each; loop++) {
printf ( "i[%d]=%s\n", loop, i[loop]);//print all the i inputs
}
for ( loop = 0; loop < each; loop++) {//free memory
free ( str[loop]);
free ( i[loop]);
}
return 0;
}
You have a few issues here.
First, while you should be using character pointers, you never allocate any memory for them. Next, when you use scanf, you should not be passing the address of the pointers but the pointers themselves. This is an easy mistake to make since you must pass the address when using scanf with integer types.
int main() {
char str[255];
char i[255];
int n = 1;
while (n == 1) {
n = scanf("%m[^':']:%m[^':']:", str, i);
}
printf("# inputs read: %d\n", n);
printf("%s\n", str);
printf("%s\n", i);
}