3
#include <stdio.h>

int main(int argc, char **argv){
    int c;
    char str[10];
    while ((c=getchar()) != '\n') {
        scanf("%s",str);
    }

    printf("%s\n", str);
}

If the input is "Data", the output is "ata" where the "D" is missing. Can't figure out why. Any explanation?

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53

4 Answers4

2

In your program,

while ((c=getchar()) != '\n') {
        scanf("%s",str);
}

the getchar will absorb the first character, then the scanf will take all but the last '\n', which will end the while loop.

Thus str misses the first char.

Change to

do  {
        scanf("%s",str);
} while ((c=getchar()) != '\n');

to get the whole string. Or simply remove the loop and getchar()...

Déjà vu
  • 28,223
  • 6
  • 72
  • 100
1

When you use getchar() to get the character, it takes the first character "D" of input "Data".

The actual value of str variable is "ata".

Use putchar() and try this code snippet to verify the values of your variable c and str.

#include <stdio.h>

int main(int argc, char **argv){
    int c;
    char str[10];
    while ((c=getchar()) != '\n') {
        //to display the value of c
        putchar(c);
        scanf("%s",str);
    }

    printf("%s\n", str);
}
Om Mishra
  • 52
  • 9
1

Your getchar is consuming the first letter of your string, while the scanf is consuming the rest in a single iteration.

The difference between scanf and getchar is that scanf is a formatted method of reading input from the keyboard while getchar reads a single character from the keyboard at a time.

So either use the getchar in the while loop, or use scanf (with no loops) if you know what the input format is supposed to be, which you can configure with the format specifiers.

getchar: http://www.cplusplus.com/reference/cstdio/getchar/

scanf: http://www.cplusplus.com/reference/cstdio/scanf/

The difference: C getchar vs scanf

Azmat
  • 97
  • 1
  • 11
-2

getchar() function used to only fetch one character not whole String

If you want to fetch whole string than simple remove loop

scanf("%s",&str)// str is simple variable or array

And onther solution is

while(c=getchar()!='\n')
{
  str[i]=c;
}
str[i]='\0';
Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
  • `str is simple variable or array` - How do you be able to store a string in a single variable? – RobertS supports Monica Cellio May 16 '20 at 08:02
  • @RobertSsupportsMonicaCellio I don't understand what you are saying. "single variable" is "an array" here which can store a string because a string is an array of characters. – Ardent Coder May 16 '20 at 09:15
  • @ArdentCoder A variable (scalar type) isn´t an array (aggregate type). – RobertS supports Monica Cellio May 16 '20 at 09:16
  • @RobertSsupportsMonicaCellio I'm not familiar with the formal terminology, but see what the answerer had said: "str is simple variable or array". It can be seen that she meant to say "array" because sometimes we use "or" to indicate an alias of the previous word. And I still don't understand how an array is not a variable. – Ardent Coder May 16 '20 at 09:21
  • @RobertSsupportsMonicaCellio I've looked upon "scalar type" and "aggregate type". Those are more like datatypes, which is not related to "*variable* vs array" in this context. And I'm not saying that this answer is entirely correct, I've simply upvoted it to counter a downvote which might have stood for a misinterpretation of words. – Ardent Coder May 16 '20 at 09:35
  • @ArdentCoder To view it from a technical point of view, something like a "*variable*" doesn´t even exist since the C standard. It is a common used word for a single entity of memory according to a specific datatype, which can hold a *variable* value. - The standard calls something like that an "object". -> "*object - 1. region of data storage in the execution environment, the contents of which can represent values 2. Note 1 to entry: When referenced, an object can be interpreted as having a particular type; see 6.3.2.1.*". – RobertS supports Monica Cellio May 16 '20 at 09:44
  • @RobertSsupportsMonicaCellio Lol that's two different perspectives to the same thing. So it boils down to its interpretation in this scenario: Which tone is better while explaining things: common words or technical words? Thus, accusing the answerer purely in terms of that is quite a bit rude imho. If you had instead mentioned the inaccuracies in the code, it would have been more beneficial. – Ardent Coder May 16 '20 at 09:52
  • @ArdentCoder BTW, I didn´t downvoted the question myself; I just pointed OP to correct their answer. – RobertS supports Monica Cellio May 16 '20 at 10:01
  • @RobertSsupportsMonicaCellio "isn't possible"? [Godbolt](https://godbolt.org/z/a4SE3N). Let me show you some inaccuracies: missing semicolon in that statement, and mainly a lot in the second part of the answer. – Ardent Coder May 16 '20 at 10:02
  • @ArdentCoder I didn´t said that it is the one and only issue in the code. Your experiment works because `str` is an array. It is not a "*simple variable*". If you would repeat the same experiment with `char str;` instead, the behavior would be undefined, because parts of the string are written beyond the bounds of `str`. Even if you just provide one single character and press Enter. – RobertS supports Monica Cellio May 16 '20 at 10:12
  • @RobertSsupportsMonicaCellio I've [already clarified](https://stackoverflow.com/questions/61832443/why-doesnt-the-first-letter-get-into-the-array-if-this-program-is-used/61832942?noredirect=1#comment109369371_61832942) what the answerer meant when she said that statement. And my experiment was based on the code written in the question and the answer, nothing more and nothing less. *Re: "I didn´t said that its the one and only issue in the code."*: That's not an issue in the code, that's a negligible issue in the communication. – Ardent Coder May 16 '20 at 10:17
  • @ArdentCoder This whole discussion will go to nowhere. OP seems to not react at all - thus won´t edit their answer. We both have for sure better things to do than to discuss this here. If the meaning of "*variable*" isn´t clear to you, feel free to ask a separate question instead of discussing that in the comment section to an answer to a different question. I would like to participate on that question as well. – RobertS supports Monica Cellio May 16 '20 at 10:33
  • That first part is exactly what I meant. Your initial comment in this section was opinion based (debate of terms), which didn't clarify what was wrong in the code. And I had already said that this answer was not completely right in one of the middle comments. *Re: "And a variable isn´t an array. Stop."* When did I say that? You have rearranged my point: "A variable can be an array". – Ardent Coder May 16 '20 at 10:39
  • @RobertSsupportsMonicaCellio I agree with that. Feel free to ask one yourself because the community will greet me with downvotes if I ask one. I don't have any money to buy the Standard and quote points from it to make my questions look better. – Ardent Coder May 16 '20 at 10:46
  • 1
    @ArdentCoder If a question is focused, clear and shows research effort and of course is on-topic, it won´t get downvoted. - You don´t need to buy hardcopies of the official release. Use the drafts which almost contain the same content. Here f.e. C11. -> http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf - Have fun at reading :-) – RobertS supports Monica Cellio May 16 '20 at 10:54
  • @RobertSsupportsMonicaCellio I am from a small village and never had access to such books. Thanks for it <3 – Ardent Coder May 16 '20 at 10:57
  • @ArdentCoder I listed personally all draft links to C and C++ standards in this answer: https://stackoverflow.com/a/83763/12139179 – RobertS supports Monica Cellio May 16 '20 at 10:59
  • @RobertSsupportsMonicaCellio Yah, I had seen it once. But left soon when I saw the $ behind links lol. Oops, I should have read deeper. Thanks, I got the books. – Ardent Coder May 16 '20 at 11:01
  • 1
    @ArdentCoder Well, now you have occupied weekends ;-) – RobertS supports Monica Cellio May 16 '20 at 11:02
  • 1
    @ArdentCoder One tip: save the question to your bookmark questions or as I do it (look on my profile for reference) list links to interesting questions and/or answers on your profile. - I flagged this answer for low-quality so I guess it will be deleted in the next days (if OP won´t edit it accordingly). – RobertS supports Monica Cellio May 16 '20 at 11:06
  • @RobertSsupportsMonicaCellio Oh yes, and I was waiting for you to say "if OP won´t edit it accordingly" :p And thanks for your time, happy coding :) – Ardent Coder May 16 '20 at 11:14
  • @RobertSsupportsMonicaCellio I think I should reveal that I actually came here via the review queue and was the one who actually declined the original flag by editing the post, for this [reason](https://meta.stackoverflow.com/a/345029/10251345). If you have any reasons against it then I'll support your flag. – Ardent Coder May 16 '20 at 12:15
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/213995/discussion-between-ardent-coder-and-roberts-supports-monica-cellio). – Ardent Coder May 16 '20 at 12:15