0

I got used to printf and variables in C, then I started to use the scanf function, here's the code (shamelessly stolen from fresh2refresh.com)

#include <stdio.h>
int main()
{
   char ch;
   char str[100];
   printf("Enter any character \n");
   scanf("%c", &ch);
   printf("Entered character is %c \n", ch);
   printf("Enter any string ( upto 100 character ) \n");
   scanf("%s", &str);
   printf("Entered string is %s \n", str);
}

Except that it doesn't run, neither on the vscode output or cmd. it doesn't even print the "Enter any character" from line 5, it show that the code is running, but doesn't even accept inputs (and will only halt once I click the Stop Code Run button)

any tips?

Steve Summit
  • 45,437
  • 7
  • 70
  • 103
  • There's nothing (well, not much) wrong with your code. The problem is probably in your compilation/run environment. First thing to try: sprinkle `fflush(stdout)` after your `printf` calls. – Steve Summit Dec 17 '21 at 19:04
  • 4
    `scanf("%s", &str);` is wrong. It should be `scanf("%s", str);`. But I doubt that's preventing it from working properly. (And before you say "But I thought I always needed `&` with `scanf`, yes, that's true, except that `%s` is an exception to that rule. This is one of the many, many annoying things abut `scanf`.) – Steve Summit Dec 17 '21 at 19:05
  • nvm it still doesnt accept inputs – ChaoticNeutralFurry Dec 17 '21 at 19:06
  • Just so you know: `scanf` is **not** one of the smaller summits you need to reach before finally reaching the peak of being a seasoned C programmer. Seasoned C programmers don't use `scanf` at all, for anything. The only reason you need `scanf` is so that you can complete the exercises in beginning C classes. The *less* time you can manage to spend learning about `scanf`, the better. It's a complete dead end. – Steve Summit Dec 17 '21 at 19:08
  • Why do you say that `scanf()` doesn't work and then continue to say not even the `printf()` works? That wouldn't have happened if you had *first* extracted a [mcve]. – Ulrich Eckhardt Dec 17 '21 at 19:09
  • 1
    the printf works now, but the scanf doesnt – ChaoticNeutralFurry Dec 17 '21 at 19:10
  • I tested your program on my computer and it worked perfectly fine, except for the warning I got about "`format specifies type 'char *' but the argument has type 'char (*)[100]'`". But it did accept inputs, and it did print outputs. – Steve Summit Dec 17 '21 at 19:10
  • 2
    @SteveSummit, I consider myself a seasoned C programmer, and I occasionally use `scanf`. Indeed, I consider it a mark of my seasoning that I know when that's a reasonable thing to do (not particularly often) and how to make `scanf` work safely and reliably for me when I do choose to use it. – John Bollinger Dec 17 '21 at 19:12
  • 1
    Please show exactly what you entered. Did you type one character key, and then press the key? Nothing will happen until you press . – Weather Vane Dec 17 '21 at 19:12
  • well im using vscode 1.63.2 in a windows 10 notebook – ChaoticNeutralFurry Dec 17 '21 at 19:12
  • @UlrichEckhardt This looks like a nicely minimal example to me. There's no indication the posted code is other than that the OP is running, and every indication that there's something wrong with the OP's environment. – Steve Summit Dec 17 '21 at 19:13
  • There is *one* indication: the `printf("Enter any character \n");` isn't line 5 as claimed but line 6. – Weather Vane Dec 17 '21 at 19:15
  • 1
    @ChaoticNeutralFurry I don't know anything abut vscode, but I see lots of questions like yours. I don't know if its defaults or wrong, or there's an easy configuration mistake to make, or what, but we often hear that it's failing to run even the most basic programs. This is appallingly frustrating, because if you're just learning, you naturally assume you must have made a mistake. – Steve Summit Dec 17 '21 at 19:15
  • first i tried the good ol jvndlfjkwd lkuduy32nhdc wvfdv m, NOTHING. then the vfmdmvdvf *enter*, still nothing. *enter* gfdgdfojmodvdfk *enter*, same thing. – ChaoticNeutralFurry Dec 17 '21 at 19:15
  • Style guide: avoid putting spaces before newlines — they aren't desirable in general. – Jonathan Leffler Dec 17 '21 at 19:16
  • 1
    For safety, your lines `printf("Enter any string ( upto 100 character ) \n") scanf("%s", &str);` should be `printf("Enter a string without spaces (up to 99 characters)\n"); scanf("%99s", str);` — and the changes shown fix many problems. – Jonathan Leffler Dec 17 '21 at 19:18
  • it took a really long while to actually set vscode up C, actually thats the reason i kinda gave up on C#, but for some reason its extremely simple with python – ChaoticNeutralFurry Dec 17 '21 at 19:19
  • @ChaoticNeutralFurry When I run your program and type "vfmdmvdvf *enter*", it prints "Entered character is v" and immediately "Entered string is fmdmvdvf". (It also prints both prompts.) This is as I would expect. I think the problem is not with your code, but with your coding environment. – Steve Summit Dec 17 '21 at 19:19
  • I don't see anything wrong with the code beyond the error that Steve pointed out in his first comment (which I agree probably does not cause any misbehavior in practice anyway). After correcting that, the program compiles for me without any warnings and behaves as seems to be intended when I run it from the command line. I am using Linux, but I don't see any reason to suppose that the program would exhibit different behavior on a different OS or a different conforming C implementation. – John Bollinger Dec 17 '21 at 19:19
  • @JohnBollinger Opinions vary, I suppose. Somehow I learned C without ever using scanf that I remember. I only learned about it (and its many perverse foibles) when I started answering frequent questions — and, boy, are questions about scanf frequent! The vast number of hours wasted by beginning C programmers on this misbegotten function, to no purpose, is mindblowing. You need a good way of reading simple ints into simple programs, it's true, and scanf *almost* fits the bill — but it ends up being, as someone said, square training wheels. (But I do admit: I use it once in a while, too.) – Steve Summit Dec 17 '21 at 19:26
  • 1
    so basically my vscode c is f'd up. any tips? i installed gcc with mingw and path variables – ChaoticNeutralFurry Dec 17 '21 at 19:26
  • @ChaoticNeutralFurry It sounds like it. But you said programs with just printf do work? That's really weird. I wish I could give you tips on vscode, but I've never used it. – Steve Summit Dec 17 '21 at 19:27
  • the *printf*s work absolutely fine, no errors whatsoever – ChaoticNeutralFurry Dec 17 '21 at 19:29
  • What if you run `#include int main() { char c = getchar(); printf("you typed %c\n", c); }`? Then run it and type something like "x *enter*". – Steve Summit Dec 17 '21 at 19:29
  • When you say the printfs work fine — what do they say that you enered? – Steve Summit Dec 17 '21 at 19:31
  • doesnt work either, it doesnt show anything i type, enter doesnt work – ChaoticNeutralFurry Dec 17 '21 at 19:31
  • quick thing whats enered? – ChaoticNeutralFurry Dec 17 '21 at 19:32
  • typo: entered. So when you say "the printfs work", you mean it printed "Enter any character", and then nothing after that? (The first printf worked, but the other three didn't?) – Steve Summit Dec 17 '21 at 19:35
  • Shot in the dark: instead of the Enter key, try holding down the Control (Ctrl) key and typing M or J. – Steve Summit Dec 17 '21 at 19:36
  • in order: exactly, nothing after it. ctrl m or j doesnt work either. also, ```#include int main() { int somethingfunny = 4; printf("hehe %d yeeter than %d", somethingfunny, (somethingfunny * 2)); }``` works like a charm – ChaoticNeutralFurry Dec 17 '21 at 19:40
  • 1
    There's a super fundamental premise, across all of C and Unix, that `stdin` (which is what `getchar` and `scanf` read from) is connected to your keyboard by default. It sounds like, somehow, your vscode installation has not managed to achieve that. Whether there's something as simple as a "connect stdin to keyboard" checkbox in vscode's configuration, that's accidentally been unchecked, I couldn't say. – Steve Summit Dec 17 '21 at 19:50
  • how can i check this? – ChaoticNeutralFurry Dec 17 '21 at 19:51
  • How can you check vscode's configuration? I have no idea. (Actually, you *have* checked that: your tests show that your installation of vscode can *not* read input from the keyboard.) I would suggest you ask a brand-new question, not even mentioning `scanf`, titled "vscode can't read input for some reason, any tips?" or something like that. – Steve Summit Dec 17 '21 at 19:55
  • ChaoticNeutralFurry, Debug step: Set initial values: `char ch = '?'; char str[100] = "ABC";`, comment out all the `scanf()` statements and run again. Run. Is output as expected? – chux - Reinstate Monica Dec 17 '21 at 21:27
  • 1
    ChaoticNeutralFurry, "Enter any string ( upto 100 character )" is off by one. `char str[100];` is large enough to store a _string_ of up to 99 input characters, not 100. If you try more, bad things can happen. – chux - Reinstate Monica Dec 17 '21 at 21:29

7 Answers7

1

The line

  scanf("%s", &str);

Is incorrect - it should be

  scanf("%99s", str);

So

  1. It has bounds - i.e. not array over bounds
  2. It is passing a char *

BTW - Might be a good idea to check the return value from scanf

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • couldnt get to that part to test, but once i get, ill test it – ChaoticNeutralFurry Dec 17 '21 at 20:45
  • 1
    @ChaoticNeutralFurry The point is that while I doubt the extra `&` is causing your problem, theoretically it does make your program's behavior undefined, so theoretically anything can happen. So to remove all doubt, you need to make that change, and rerun your program, and tell us whether you're still seeing the same result. – Steve Summit Dec 17 '21 at 20:50
1

You can choose: Run->Add Configuration... -> launch.json change this: "externalConsole": true,

Ngo Thanh Nhan
  • 503
  • 2
  • 5
  • 17
0

Recently I encountered the same problem.

So here's the fix :

  1. In visual studio code, go to extensions and download "Code Run by Jun han"
  2. Then go to the extension setting >> scroll down >> and click on Run in Terminal
  3. You may reopen your vs code or else skip this step.
  4. Now, try running the code again.

Hope it helps!!

0

I had the exact same problem and what worked for me was installing Code Runner and then go to the setting of your visual studio code. Search "Run In Terminal" and then make sure the Code Runner: Run in Terminal box is checked.

enter image description here

That fixed my issue.

halfer
  • 19,824
  • 17
  • 99
  • 186
-1

format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[100]’ [-Wformat=] scanf("%s", &str);

Strings are represented as Array of characters thus array name is an identifier(implicit conversion to pointer) is the address of first element thus no need to specified '&' in case of reading strings.

Its clear from warning that it can't convert from char (*)[100] to char *

mohammed yaqub
  • 100
  • 1
  • 8
-1

In C, a string is the address of the character buffer which is why we do not need "&" with the variable. Code with solution

pooja
  • 81
  • 3
  • Please post your code directly to the answer, no need of adding extra URLs that can become invalid in future. – Tyler2P Dec 18 '21 at 11:53
-1

My English is poor. I wish I can help you!!

scanf("%s", &str); this sentence is false. Do you know pointers, or Memory address?

If you know, suppose you are the creator of scanf. What you need to do is read what the user write in the screen and copy them to the space of the second argument. So, you don't care about the value of the second argument. What you care about is the address of the second argument. Then you can access this memory space. So, when the second argument is a variable, such as int a, you need to "&a". But str itself can be a address. So it do not need "&"

Andrew Chen
  • 71
  • 1
  • 9
  • Thanks, but as the bounty notice says, the question is not about the superfluous & in scanf("%s", &str). – Steve Summit Dec 20 '21 at 11:19
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 20 '21 at 13:52