I’m trying to get the _strrev function to work but when I put my string into a function it doesn’t seem to work, just when I'm out of the function..
I’m getting so frustrated because I'm not getting anywhere with this..
Here's my code so far
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverse(char *string) {
char *str, temp;
int begin = 0, end = 0;
char word[64];
int jaja = 0;
printf("Your string from the function is %s\n", string);
printf("%s\n", _strrev(&string)); //And why isnt this working
jaja = strlen(string);
printf("Your string has %d characters\n", jaja);
}
int main()
{
char *str;
scanf("%s", &str);
printf("%s\n", _strrev(&str)); //How come this works
reverse("Okay");
getchar();
return(0);
}
So I would love some guidance where my mistake is, I seriously cant find it.
According to MSDN The prototype for _strrev is
char *_strrev(
char *str
);
If you have a char *string you must call it like this :
printf("%s\n", _strrev(string));
In this case
printf("%s\n", _strrev(&string));
you are passing a char**
To answer the question you posted in your code comments:
int main()
{
char *str;
scanf("%s", &str);
printf("%s\n", _strrev(&str)); //How come this works
That works because you're lucky, as your call to scanf() places whatever it reads into the actual memory used for the pointer str, and you're not entering enough data to cause problems. Try entering a really long string when running this program and it won't work as well.
You need to actually have a char buffer to read data into, like this:
int main()
{
char str[256];
scanf("%s", str);
printf("%s\n", _strrev(str));
or
int main()
{
char *str = malloc( 256 );
scanf("%s", str);
printf("%s\n", _strrev(str));
And as pointed out in the comments to the question, you can still overrun your buffer.
Related
I'm very new to C but am trying to make a function to ask the user a question using scanf, any suggestions of how I should go about this, this is currently what I have.
#include <stdio.h>
char name[100];
int num, days;
int askQ(char *question, char *x, char *answer) {
printf("%s", question);
fflush(stdout);
scanf(x,&answer);
return 1;
}
int main() {
askQ("hello? | ", "%s\n", &name);
printf("%s", name);
return 0;
}
A couple of things make this a bit tricky. Your requirement for an arbitrary format string makes it difficult to know how arguments are to be passed to scanf(). E.g. an int argument will require that you pass the address of the receiving variable to scanf(), whereas a string does not require the address because the "string" is already a pointer.
Similarly you should check the return value from scanf() to ensure that the input was processed as expected - that's hard for an arbitrary format string.
Perhaps, if you really need arbitrary input parsing you can use vscanf(), but at your level I would not recommend that.
If you choose to keep it simple so that you simply have a prompt with a single string response then you might do this:
#include <stdio.h>
int askQ(char *question, char *format, char *answer) {
printf("%s", question);
int i = scanf(format, answer);
return i == 1;
}
int main() {
char name[100]; // accept up to 100 chars input
if (askQ("hello? | ", "%s", name))
printf("Response: %s\n", name);
else
printf("Failed to get valid response from user\n");
}
I am running the following c program:
#include <stdio.h>
int main() {
char str1;
printf("What is your name? ");
scanf("%s.", str1);
printf("Hi there %s.", str1);
return 0;
}
But this what it returns:
What is your name? Varun
Hi there (null).
Why does it say (null)? Please answer.
You have multiple mistakes here:
You use %s for a char variable.
You're not passing a pointer to scanf function. You're just passing a garbage value.
You introduced an undefined behavior. And you should have some compile-warnings that tells you that you have mistakes.
char str1; you have space for only 1 char , that's not much , try replacing with char str1[30]; and try again.
Try this instead:
#include <stdio.h>
int main() {
char str1[1000]; // <-- here are the changes
printf("What is your name? ");
scanf("%s.", str1);
printf("Hi there %s.", str1);
return 0;
}
To use strings in c, you need to create a char array with a specific size
char arr[1000]; // array of size 1000, it can contain a string of 1000 letters
then to fetch the string you have to use
scanf("%s", arr);
then to print it back use
printf("%s", arr);
#include <stdio.h>
#include <malloc.h>
int main() {
char *str;
str = (char *)malloc(sizeof(char) * 10);
printf("What is your name?");
scanf("%s", str);
printf("Hi there %s.", str);
return 0;
}
I think you should do like this, you should understand char and string.
I am learning C and I simply wanted to output the first char of the string that the user inputs. Somehow it doesnt work? I also got no error message. This must be a really simple question, but I dont get it.
#include <stdio.h>
int main(void)
{
char input[200];
char test;
printf("Text input: ");
scanf("%s", input);
test = input[0];
printf("%s", test);
return 0;
}
You need to use %c to print a char. %s is for null-terminated strings, i.e. char arrays. The code below works fine for me.
#include <stdio.h>
int main() {
char input[200];
char test;
printf("Text input: ");
scanf("%s", input);
test = input[0];
printf("%c\n", test);
return 0;
}
Try this
#include <stdio.h>
int main() {
char input[200];
char test;
printf("Text input: ");
scanf("%s", input);
test = input[0];
printf("%c\n", test);
return 0;
}
This works. U need to use %c rather than %s to print characters
I have this little problem, and can't solve it.
The thing is that I'm trying to load all four strings in the function LOAD by asking the user to insert it. Everything seems fine and I don't get any compiler error. But eaf stays empty. I tried many ways, even replacing scanf with gets, gets_s, fgets, but nothing changes.
#include <conio.h>
#include <stdio.h>
#include <string.h>
void LOAD(char eaf[], char initials[], char finals[], char symbols[]);
int COMPARE(char s[], char eaf[]);
int main()
{
char eaf[10],initials[1],finals[10],symbols[5];
LOAD(eaf, initials, finals, symbols);
return 0;
}
void LOAD(char eaf[], char initials[], char finals[], char symbols[])
{
printf("Insert states of the optimized AFD\n");
scanf( " %s", eaf);
printf("Insert AFD initial state\n");
do
{
scanf( " %s", initials);
} while (COMPARE(initials, eaf));
printf("Insert final state(s)\n");
do
{
scanf( " %s",finals);
} while (COMPARE(finals, eaf));
printf("Insert the language symbols\n");
scanf( " %s",symbols);
}
int COMPARE(char s[], char eaf[])
{
int i;
char *ptr;
for(i; i < strlen(s); i++){
printf("%d\n", i);
while(ptr==NULL){
ptr = strchr(eaf, *s);
}
}
if (ptr == NULL) return 1;
else return 0;
}
What am I doing wrong? This is just a small part of a bigger program, but the rest of it is useless because eaf is empty. I thought that the problem was using scanf, but as I said other functions didn't work as well. I hope anyone can help me. Thanks
edit: I checked by strlen(eaf)
Using "scanf" for input is dangerous, and you've walked right into that danger. You're allowing it to overwrite the contents of "eaf" when you ask it to read initials as a string and it adds the terminating 0.
Ultimately, the string is empty because you got your array dimensions wrong. You gave "initials" an array size of 1 which does not provide space for the trailing '\0' C-string terminator.
See the live demo of this code on ideone:
#include <stdio.h>
void report(char* eaf, char* initials, char* foo)
{
printf("eaf = %p, initials = %p, foo = %p\n", eaf, initials, foo);;
printf("*eaf = %d, *initials = %d, *foo = %d\n", eaf[0], initials[0], foo[0]);
}
void load(char eaf[], char initials[], char foo[])
{
printf("load\n");
report(eaf, initials, foo);
printf("Enter EAF\n");
scanf(" %s", eaf);
report(eaf, initials, foo);
printf("Enter initial state\n");
scanf(" %s", initials);
report(eaf, initials, foo);
}
int main(int argc, const char* argv[])
{
char eaf[10], initials[1], foo[10];
report(eaf, initials, foo);
load(eaf, initials, foo);
report(eaf, initials, foo);
return 0;
}
You should have walked thru this in the debugger and watched the values of "eaf" and "initials" to see what happened as you progressed.
Do you have to write this program in C? It seems that using a scripting language such as perl or python might be easier for you.
Here is a working C method to start solving the problem, note that I didn't actually fix the problem, but it will make it easier to see it.
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
void report(char* eaf, char* initials, char* foo)
{
printf("eaf = %p, initials = %p, foo = %p\n", eaf, initials, foo);;
printf("*eaf = %d, *initials = %d, *foo = %d\n", eaf[0], initials[0], foo[0]);
}
void load(const char* label, const char* into, size_t intoSize)
{
assert(intoSize > 1); // can't store a string in 1 character.
printf("%s\n", label);
char input[1024] = "";
fgets(input, sizeof(input), stdin);
size_t len = strlen(input);
// strip trailing \n off.
if (len > 0 && input[len - 1] == '\n') {
input[--len] = 0;
}
// abort on empty input
if (len <= 0) {
fprintf(stderr, "Invalid input - terminated.\n");
exit(1);
}
if (len >= intoSize) {
fprintf(stderr, "Invalid input - length was %u, limit is %u\n", len, intoSize - 1);
exit(2);
}
strncpy(into, input, intoSize);
}
int main(int argc, const char* argv[])
{
char eaf[10], initials[1], foo[10];
report(eaf, initials, foo);
load("Insert states of the optimized AFD", eaf, sizeof(eaf));
report(eaf, initials, foo);
load("Insert initial AFD state", initials, sizeof(initials));
report(eaf, initials, foo);
printf("eaf = %s\ninitials = %s\n", eaf, initials);
return 0;
}
See live demo on ideone here.
You're format string in scanf is most likely the culprit; you have an extra space before the %s.
Change:
scanf( " %s", eaf);
to
scanf( "%s", eaf);
for all your scanf's.
Its not putting your input into eaf because it is looking for a string of the format " blahblahblah" (note the space in the beginning) instead of "blahblahblah"
Edit
Disregard the above,
whitespace: Any whitespace characters trigger a scan for zero or more whitespace characters. The number and type of whitespace characters do not need to match in either direction.
Also, you should initialize i in your COMPARE function (I don't understand how you're not getting an angry warning from your compiler), I ran your code with no modifications and strlen(eaf) returned the correct count (just after the scanf).
#include <stdio.h>
#include <string.h>
int main()
{
char s[15];
int i,j,n,*str;
printf("Enter a string");
scanf("%s",str);
n=strlen(str);
for(i=0;i<n;i++)
{
str[n]=str[0];
for(j=0;j<n;j++)
{
str[j]=str[j+1];
}
str[n]='\0';
printf("\n %s",str);
}
return 0;
}
this program gives me all possible rotations of string
can anyone explain str[n]=str[0] and str[j]=str[j+1] meaning
instead of taking n=strlen(s) can we use n=strlen(str)
plz explain
This rotates the string. The way it does so is by moving the first character to the last place by doing str[n] = str[0] (str[n] is the string-terminating null character '\0', then shifting the whole string down one (str[j] = str[j+1]), then replacing the null at the end (str[n]='\0').
This code would, if it were using s, cause a buffer overrun if the string is longer than 14 characters. However, there's also a logic error in the code: it should be either initializing str (as a char* not int*) or scanning into s with a length bound. For instance:
scanf("%14s", s);
or
str = (char*)malloc(500);
scanf("%500s", str);
instead of taking n=strlen(s) can we use n=strlen(str)
Actually, since str is an int-pointer that is not initialized anywhere, all uses of str should be replaced by s (it's probably just a typo).
#include <stdio.h>
#include <string.h>
int main()
{
char s[15];
char tmp_var;
int i,j,n,*str;
printf("Enter a string");
scanf("%s",str);
n=strlen(str);
for(i=0;i<n/2;i++)
{
tmp_var = str[i];
str[i] = str[n-i];
str[n-i] = tmp_var;
}
printf("\n Rotated String is %s \n",str);
return 0;
}