我正在尝试使用 while 循环将用户输入写入 txt 文件。
但由于某种我不知道的原因,while 循环不会通过单击“输入”而停止。 当我单击“输入”时,我看到“while 循环已执行”,因此我知道 while 循环再次迭代,即使我想停止 while 循环。
如何以正确的方式做到这一点?
P.S:我使用教授推荐的 Microsoft Visual Studio。
#include <stdio.h>
#include <string.h>
void main()
{
//writing to file
char write[100];
char fileName[100];
printf("give a name for file: ");
gets_s(fileName,99);
strcat(fileName,".txt");
FILE* pF = fopen(fileName, "w");
printf("what needs to be written?\n: ");
while(gets_s(write,99) != NULL)
{
printf("whileloop executed\n");
fprintf(pF,"%s\n", write);
}
fclose(pF);
}
最佳答案
每Microsoft's gets_s()
documentation ,gets_s()
在文件结束和错误条件下返回 NULL
:
Return Value
Returns buffer if successful. A NULL pointer indicates an error or end-of-file condition. Use
ferror
orfeof
to determine which one has occurred.
点击enter
键不会关闭输入流并导致文件结束条件。它只是在输入流中放置一个以换行符结尾的零长度行。
要在 Windows 上从终端执行此操作,通常必须输入 CTRL-Z
组合键。
关于c - while(gets_s != NULL) 不是由 C 编程中的 Enter 终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58965119/