String input using C scanf_s
我一直在寻找自己的答案,但找不到。
我想插入一部分程序,该程序读取" Hello"之类的字符串并存储并在需要时显示它,以便
这是给我麻烦的代码部分
1 2 3 |
我知道
根据ISO / IEC 9899:2011标准的附件K.3.5.3.2中的
The
fscanf_s function is equivalent tofscanf except that thec ,s , and[ conversion
specifiers apply to a pair of arguments (unless assignment suppression is indicated by a
* ). The first of these arguments is the same as forfscanf . That argument is
immediately followed in the argument list by the second argument, which has type
rsize_t and gives the number of elements in the array pointed to by the first argument
of the pair. If the first argument points to a scalar object, it is considered to be an array of
one element.
和:
The
scanf_s function is equivalent tofscanf_s with the argumentstdin
interposed before the arguments toscanf_s .
MSDN说类似的话(
您的代码未提供length参数,因此使用了其他一些数字。它并不能确定它会找到什么价值,因此您会从代码中得到怪异的行为。您需要更多类似的内容,其中的换行符可帮助确保实际看到输出。
1 2 3 4 |
我在大学课程中经常使用它,因此在Visual Studio(在VS2013中测试)中应该可以正常工作:
1 2 3 4 5 6 7 8 | char name[64]; // the null-terminated string to be read scanf_s("%63s", name, 64); // 63 = the max number of symbols EXCLUDING '\\0' // 64 = the size of the string; you can also use _countof(name) instead of that number // calling scanf_s() that way will read up to 63 symbols (even if you write more) from the console and it will automatically set name[63] = '\\0' // if the number of the actually read symbols is < 63 then '\\0' will be stored in the next free position in the string // Please note that unlike gets(), scanf() stops reading when it reaches ' ' (interval, spacebar key) not just newline terminator (the enter key) // Also consider calling"fflush(stdin);" before the (eventual) next scanf() |
参考:https://msdn.microsoft.com/zh-cn/library/w40768et.aspx
1 2 3 4 5 6 7 8 9 10 11 |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
您应该执行以下操作:
更新:
以下代码对我有用:
1 2 3 4 5 6 7 |
如果您使用的是Visual Studio,
转到
注意:这仅在您正在做作业或类似的工作时才有用,不建议在生产中使用。