Why scanf() always return nothing? [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hi i need help about this:
int t;
t = 1;
char abc[256];
int main() {
scanf("%s", abc);
if(abc == "google") {
printf("%s \n", abc);
system("firefox");
} else
printf("error");
}
it always return error please someone help!
i already tried scanf("%c", &abc); and i rewrote this about 5 times with the same result.
I'm new at this so this can be a very stupid thing.

if(abc == "google") {
This doesn't do what you think it does. This checks whether the pointers to those two strings are numerically equal. They never will be, because abc is allocated in the stack, and "google" is a string literal and therefore has static storage duration.
You should use strcmp like ameyCU points out.
In general, don't use scanf like this, the code you wrote is vulnerable to buffer overflow attacks if someone passes a large string.
You might want to look at this nice post about how to use scanf safely. How to prevent scanf causing a buffer overflow in C?

You can't compare the contents of two character arrays with ==. == will just compare the memory addresses of the arrays (after array-to-pointer decay).
Use strcmp instead:
if (strcmp(abc, "google") == 0) ...

The constant string "google" reside in the .rodata section of your program and if you compile with all warning -Wall you get this warning
google.c:10:12: warning: comparison with string literal results in unspecified behavior [-Waddress]
if(abc == "google") {
and this code is equivalent with
const char* const google_str = "google";
if(abc == google_str)
Here both the string "google" and the address to that string is constant. So you see you are doing a pointer comparison and not a string comparison.
printf("%p == %p\n", abc, google_str);
This code will show you that abc reside on the stack and that google_str reside in the .rodata section. String comparison should be done with
if(0 == strcmp(abc, "google")) {

<code>
if(abc == "google")
</code>
would work in object oriented languages like java and dot net
in c cpp you have to use inbuild library functions of String like strcpy,strcmp
<code> int strcmp(const char *str1, const char *str2) <code>
compares the string pointed to, by str1 to the string pointed to by str2.
So you will modify your code as
#include <stdio.h>
int t;
t = 1;
char abc[256],a[256];
int main()
{
strcpy(a,"google");
scanf("%s", abc);
if( strcmp("abc","google")==0 ) {
printf("%s \n", abc);
printf("firefox");
} else
printf("error");
return 0;
}

Related

How to use words in c language arrays? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm learning C language and using VBCC as compiler with C99 standard. Trying to figure out how to print multi character elements from array, but printf warn me the type of argument is not matching. It's "just" a warning but i want to understand what i'm doing wrong. Here is the code:
#include <stdio.h>
int main(int argc, char const *argv[]) {
const char* s[] = {"aa","hey","2","1","111","\0"};
int a = 0;
do {
printf("%p\n",&s[a]);
a = a + 1;
} while (s[a] != '\0');
return 0;
}
It's "just" a warning
Well, yes, the compiler may only emit a warning, but it doesn't mean that what you are doing is not an error. Indeed, most of the time it is. As a novice C programmer, you should basically always treat warnings as errors.
What you're doing here:
const char* s[] = {"aa","hey","2","1","111","\0"};
Is declaring an array of char* (char pointers), and assigning to each of the pointers in the array the address of a valid string (provided in the initializer {...}).
This is the same as doing:
const char *s[6];
s[0] = "aa";
s[1] = "hey";
// ... and so on
Each of the strings will be automatically NUL-terminated with the \0 terminator, which is implicit when using the syntax "string literal". The last string that you are adding is unnecessary and empty, and it also contains two terminators, the one you explicitly add and the one implicitly added by default.
Now, to the errors. What you are doing here:
printf("%p\n", &s[a]);
Is incorrect. If you want to print the a-th string, you already have a pointer to it in s[a], so you don't need to take the address (&) again. Another error is using the %p format specifier (I assume you changed it because the compiler told you so), which is not for strings, but for generic pointers (in this case is correct since &s[a] is actually a pointer, but remember that you want to print a string). In the end the above line compiles fine, but it's not what you want. The correct syntax is:
printf("%s\n", s[a]);
The real error in your code is here:
while (s[a] != '\0');
Here, you are comparing a string with a char literal (namely the terminator). You cannot do this, since the two types are different. If you want to terminate your array with a correct value that can then be compared, you can use NULL, since it's an array of pointers (char*).
Another logical error is that you are using a do {...} while cycle, and checking if you reached the end only after printing. In the specific case of your program (with an array of 6 strings) nothing bad happens, but if your array is empty (e.g. char *s[] = {NULL};) you will try to print the first element anyway, which is an error.
Here's the code with the corrections applied:
#include <stdio.h>
int main(int argc, char const *argv[]) {
const char* s[] = {"aa", "hey", "2", "1", "111", NULL};
int a = 0;
while (s[a] != NULL) {
printf("%s\n", s[a]);
a = a + 1;
};
return 0;
}
All strings in C end with zero. You have a table of pointers here and as a marker you should use NULL.
https://godbolt.org/z/KJCdsi
#include <stdio.h>
int main(int argc, char const *argv[]) {
const char* s[] = {"aa","hey","2","1","111", NULL};
int a = 0;
do {
printf("s[%d] = %s\n", a, s[a]);
a = a + 1;
} while (s[a]);
return 0;
}
Use the "%s" format specifier for printing strings, and remove the & reference operator.
printf("%s\n",s[a]);

trying to create a function in c that takes in user input and returns a string of char [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
No matter what I try I get an error. I'll remove the pointer, remove the malloc, I've tried reading in the user input in dfferent ways. I come form a java background and very confused on why none of this is working. Also I am not trying to return an array of strings i am just trying to return a string or a single array of chars in c
main(){
char *c = getResources();
}
char * getResources(){
char *str = (char *) malloc(sizeof(char) * 3);
fgets(str, sizeof(str), stdin); /* read in a line */
return *str;
}
There are many errors in your code.
The first one is the return value of the getResources() function. You are returning the value pointed by (*str), which is a single char, but you want to return the whole array.
To fix it you should write return str.
The second one is in the sizeof() operator, which is a compile-time operator. Since it is executed on compile time, it doesn't now the size of the char array malloc-ed at runtime, but only the size of the pointer itself.
Therefore you can't use it this way, but you have to replace it with the actual size of the array.
The third one is in the functions order. You can't use a function that wasn't previously declared. You can either move the full function above the main() or you can just declare it above the main() and leave the implementation behind it.
Finally, the main() function should return an integer.
Bonus tip: don't forget to free the malloc-ed pointer when you don't need it anymore
The fixed code may be as follow:
char * getResources(){
size_t str_size = 3;
char *str = malloc(str_size);
fgets(str, str_size, stdin); /* read in a line */
return str;
}
int main(){
char *c = getResources();
/* do something with c */
free(c);
return 0;
}
Your problem here is that you are returning *str instead of the pointer str:
return str;
Also, you are reading sizeof(str) characters, which is the size of a pointer, that can vary across platforms.
So instead, you need to change that to 3, the number of characters allocated for str:
fgets(str, 3, stdin);
This solution is probably among the worst pieces of C code out there, but it compiles without a warning. Please definitely make sure to read all comments made on your answer, and the info given in the answer by medalib and Andrea.
My code merely condenses all that into a chunk of stuff you can copy paste...
#include <stdlib.h>
#include <stdio.h>
// define it before you use it; a prototype would also have worked
char* getResources(){
char *str = (char *) malloc(sizeof(char) * 3);
// second param is size of input to be expected;
// you passed it the size of a pointer, which is most
// definitely not what you want
fgets(str, 3, stdin); /* read in a line */
// return the pointer; str is already declared as a pointer,
// a further * will only de-reference that again
return str;
}
int main(){
char *c = getResources();
printf("%s\n", c);
return 0;
}

String comparison in if statement not working [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 6 years ago.
I am new in C programming. Can you please advise, what's wrong with my code? It looks like the if statement is not working, and instead it's jumping and printing the else statement.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char profession;
printf("what is your profession? \n");
scanf(" %s", profession);
if(profession==“QA”)
{
printf(“Go and Test\n“);
}
else
{
printf("Do whatever you want");
}
return 0;
}
First of all, you can't compare strings like that in C. use strcmp or strncmp instead.
Secondly, in your code, profession is a char, and you want to put a string (several chars) in it. It won't work. You can create a char * (pointer on a char) (without forgetting to malloc() it) or a char [] (a char array).
Firstly, strings in C are array of characters, so you have to declare profession as a pointer, pointing to an array of characters. So that statement will look like this char* profession, secondly, you have to use a method called strcmp(char* a, char* b) that accepts two char pointers. This will return 0 if they are equal. I will include the answer, but I assume there are better ways of writing this code.
int main() {
char* profession;
char* compare = "QA";
printf("What is your profession?\n");
scanf(" %s", profession);
if(strcmp(profession, compare) == 0) {
printf("Go and Test\n");
} else {
printf("Do whatever you want");
}
return 0;
}

C Unexpected string returned from function behaviour [duplicate]

This question already has answers here:
returning a local variable from function in C [duplicate]
(4 answers)
Closed 7 years ago.
I am quite new to C and I am playing with some string operations. I have encountered quite a strange problem for me while returning a string from a function. My simple program is as follows:
int main(int argc, char* argv[])
{
char text[] = "abAB";
char* out = testString(text);
printf("Result Text: %s", out);
printf("\n");
}
char* testString(char* input) {
char* text = copyString(input);
return text;
}
The copyString function defines a simple operation to copy one string to another. It is as follows:
char* copyString(char* input) {
char output[100];
int index = 0;
while (input[index] != '\0') {
output[index] = input[index];
index++;
}
output[index] = '\0';
return output;
}
The problem is that while I am debugging the application, the string I am returning from a function seems to be OK (Visual Studio visualises it well enough) and when the printf line occurs, the string outputted on the stdout is something completely strange and unfamiliar - a smily face. Sadly, I can't post images yet in order to show you what I see in my console as output.
I am using Visual C++ Express 2010 as an IDE if this could be helpful.
You are returning a variable declared within a function, which will cease to exist outside the scope in which it is declared. Use a dynamically allocated char array and then return a pointer to it.
char* output = malloc(100 * sizeof(char));
...
return output ;
Note : You are assuming that input string is less than 100 characters. Instead of that, try passing the length of string as a parameter or use strlen. Your program will crash if input string has more than 99 characters.
Also as noted in comments, free the memory allocated when you are done using it.

Converting the output of a void method to String in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have written a void function which takes an unsigned int. Then I call this in the main function. I want the output to be a string so that I can include it in the printf statement for formatting reasons. But since I'm calling a void function, I can't tell printf that its a string (%s) or an int (%d). How can I take the output from this called void function in my main and turn it to some kind of string or integer?
A function declared as e.g. void foo(int); has no result. So you cannot convert its inexistent result to an integer or to a string.
notice that C does not have stricto sensu a string datatype. You use pointer to memory zones made of char, with the convention to zero-terminate strings.
Perhaps you want to get the output (done using printf, fprintf, fputs, and other stdio(3) standard library functions) of a function as a string. On Linux (and GNU libc) systems, you could use open_memstream(3)
Do not confuse the output of a function with its result!
So suppose you have written some outputing function like e.g.
void show_x(FILE*out, int x) { fprintf(out, "x=%d\n", x); }
Then you could get that into a string like ptrbuf (on Linux) using:
char*ptrbuf=NULL;
size_t sizbuf=0;
FILE* outmem = open_memstream(&ptrbuf, &sizbuf);
if (!outmem) { perror("open_memstream"); exit(EXIT_FAILURE); };
show_x(outmem, 42);
fflush(outmem);
printf ("now ptrbuf is %s\n", ptrbuf);
fclose(outmem);
// you later should free the `malloc`-ed `ptrbuf`
free (ptrbuf), ptrbuf=NULL;
sizbuf=0;
A void function returns nothing. Change its return type to be const char* to return a C-string:
#include <stdio.h>
const char* func_that_returns_string(unsigned int x)
{
switch (x) {
case 0: return "zero";
case 1: return "one";
default: return "who needs any other numbers?";
}
}
int main(void)
{
int i = 3;
const char* str;
str = func_that_returns_string(i);
printf("%d: %s\n", i, str);
return 0;
}

Resources