似乎有很多方法可以在C中获得用户输入.
什么是最简单的方法,需要很少的代码?
基本上我需要显示这个:
Enter a file name: apple.text
Run Code Online (Sandbox Code Playgroud)
基本上我需要询问用户文件名.所以我需要的东西只能得到用户输入的那个词.
Hos*_*ork 23
最简单的"正确"方式可能就是这一点,取自Bjarne Stroustrup的论文" 学习标准C++作为新语言".
(注意:我改变了Bjarne的代码来检查isspace()而不仅仅是行尾.另外,由于@ matejkramny的注释,使用while(1)而不是while(true)......只要我们足够邪教来编辑Stroustrup的代码,我就是在C89注释中代替C++样式.:-P)
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
void quit() /* write error message and quit */
{
fprintf(stderr, "memory exhausted\n");
exit(1);
}
int main()
{
int max = 20;
char* name = (char*) malloc(max); /* allocate buffer */
if (name == 0) quit();
printf("Enter a file name: ");
while (1) { /* skip leading whitespace */
int c = getchar();
if (c == EOF) break; /* end of file */
if (!isspace(c)) {
ungetc(c, stdin);
break;
}
}
int i = 0;
while (1) {
int c = getchar();
if (isspace(c) || c == EOF) { /* at end, add terminating zero */
name[i] = 0;
break;
}
name[i] = c;
if (i == max - 1) { /* buffer full */
max += max;
name = (char*) realloc(name, max); /* get a new and larger buffer */
if (name == 0) quit();
}
i++;
}
printf("The filename is %s\n", name);
free(filename); /* release memory */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这包括:
是否有更简单但破碎的解决方案,甚至可能运行得更快一些?绝对!!
如果将scanf用于缓冲区而不限制读取大小,则输入超出缓冲区大小,会产生安全漏洞和/或崩溃.
将读取的大小限制为,例如,只有100个文件名的唯一字符似乎比崩溃更好.但它可能会更糟; 例如,如果用户意味着(...)/dir/foo/bar.txt你最终误解了他们的输入并覆盖了一个bar.t他们可能关心的文件.
在处理这些问题时,最好养成良好的习惯. 我的观点是,如果你的要求证明了接近金属和"类C"的东西,那么考虑跳转到C++是值得的.它旨在精确管理这些问题 - 使用强大且可扩展的技术,但仍然表现良好.
scanf似乎在非敌对环境中工作.换句话说,您正在为自己制作一个简单的实用程序.
BUFSIZ通常远远超过UNIX路径名的大小限制.
#include <stdio.h>
int main(void) {
char str[BUFSIZ];
printf("Enter a file name: ");
scanf("%s", str);
printf("You entered: %s\n", str);
}
Run Code Online (Sandbox Code Playgroud)
如果需要在可能成为缓冲区溢出目标的程序中累积数据,则可能需要更多.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * prompt_and_read(const char * prompt) {
char * response;
char * bufsize;
printf("%s", prompt);
asprintf(&bufsize, "%%%us", BUFSIZ);
if((response = malloc(BUFSIZ + 1)) == NULL) {
fprintf(stderr,"out of memory\n");
exit(1);
}
scanf(bufsize, response);
free(bufsize);
return response;
}
int main ( void ) {
char * pathname;
pathname = prompt_and_read("Enter a file name: ");
printf("You entered: [%s]\n", pathname);
free(pathname);
return 0;
}
Run Code Online (Sandbox Code Playgroud)