简体   繁体   中英

Scanf String Space Issue C

Well I know many questions similar have been asked , however, I am willing to clarify if needed since my question may not be very clear. So it goes like this , say I want to get a space separated name string in C. Or in general I want to learn scanf why it behaves so weird for strings in case of File I/O in CI want to be good at debugging such stuff. I should be able to print the complete string as long as it doesn't exceed my character array limit in C. I searched a lot on the topic but if it is possible to print out the internal representation of stdin in C maybe by some way. For example :-

#include<stdio.h>
#include<stdlib.h>
int main() {
     char name[100];    // accept 100 chars

     printf("\nEnter your name: "); // This writes to stream stdout
     scanf("%100s",name);   // Specify char limit in scanf 
     while(getchar()!='\n');   // Until user presses 'Enter' else scan 100 chars
     return 0;
}

For example, suppose I type , (space)Apple(Press Enter) I can somehow print out internal representation which is I think somewhat similar to (ASCII for space)('A''p''p''l''e''\\0')'\\n' It doesn't store '\\n' in buffer I think? Now it gets a bit sophisticated to understand what happens if I give a space separated string, I know scanf discards it.

But I fail to understand how stream stays buffered and why is it so important to understand that? No offense , I am really confused on stdin file operations & scanf in C. Maybe some good example to illustrate that. I am not a very nerdy guy so I find manuals not very beginner friendly. I am definitely interested in File Input\\Output in C :):):)

scanf("%100s",name);   // Specify char limit in scanf 

specifies the maximum number of characters that can be read into name . BTW, that should be 99 since you need one element of the array for the terminating null character. However, this does not force reading of 100 characters. It will still stop when a whitespace is encountered. To read the entire line, use fgets and make sure to trim the ending newline character.

fgets(name, 100, stdin); // You use 100 here. fgets will read at
                         // most 99 characters.
int len = strlen(name);
if ( name[len-1] == '\n' )
{
   name[len-1] = '\0';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM