How to input a string using scanf in c including whitespaces

后端 未结 4 762
慢半拍i
慢半拍i 2021-01-18 00:50

Example if user enters:

My name is James.

Using scanf, I have to print the full line, i.e. My name is James., then I have to get t

4条回答
  •  庸人自扰
    2021-01-18 01:30

    @Splat has the best answer here, since this is homework and part of your assignment is to use scanf. However, fgets is much easier to use and offers finer control.

    As to your second question, you get the length of a string with strlen, and you store it in a variable of type size_t. Storing it in an int is wrong, because we don't expect to have strings of -5 length. Likewise, storing it in an unsigned int or other unsigned type is inappropriate because we don't know exactly how big an integral type is, nor exactly how much room we need to store the size. The size_t type exists as a type that is guaranteed to be the right size for your system.

提交回复
热议问题