我想让用户输入回车得到缺省值。。。。。。。

hxliurui 2003-11-27 04:20:08
char str[90];

scanf("%s", str);

if 输入回车
strcpy(str, "filename.txt");


怎么实现这个功能?
...全文
32 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
blh 2003-11-27
  • 打赏
  • 举报
回复
今天没时间,明天再说
blh 2003-11-27
  • 打赏
  • 举报
回复
那你需要用ncurse库进行console编程了
买本书看看吧
hxliurui 2003-11-27
  • 打赏
  • 举报
回复
多谢前辈指点。

顺便问一下,如果用户输入不合法的格式,可以让光标回到输入点的位置吗?

please enter file name:

如果不合法,光标回到file name:处等待重新输入


这个问题另外送分。
blh 2003-11-27
  • 打赏
  • 举报
回复
因为linux的i/o缓存机制,你要么在字符串后加\n,要么使用fflush(stdout);强制输出
hxliurui 2003-11-27
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <unistd.h>

int main()
{
int n = 0;
char str[90];

char ch;

printf("Please enter file name:"); //为什么这段提示出不来???
str[0] = 0;
while (n < 90)
{
read(0, &ch, 1);

if (ch == 10)
{
//printf("Press key is Enter!\n");
break;
}
else
{
//printf("Press key is %d\n", ch);
str[n++] = ch;
}
}
str[n] = 0;
if (n == 0)
strcpy(str, "filename.txt");
printf("%s\n", str);
return 0;
}
blh 2003-11-27
  • 打赏
  • 举报
回复
//你需要修改一下以增强安全度
#include <stdio.h>
#include <unistd.h>

int main()
{
int n = 0;
char str[90];

char ch;
str[0] = 0;
while (n < 90)
{
read(0, &ch, 1);

if (ch == 10)
{
//printf("Press key is Enter!\n");
break;
}
else
{
//printf("Press key is %d\n", ch);
str[n++] = ch;
}
}
str[n] = 0;
if (n == 0)
strcpy(str, "filename.txt");
printf("%s\n", str);
return 0;
}
hxliurui 2003-11-27
  • 打赏
  • 举报
回复
输完字符串后输回车,得到输入的字符串
什么也不输直接按回车得到缺省的字符串。

我表达错了,对不起

快点行吗?我急。。。。。。。。。。。马上给分


blh 2003-11-27
  • 打赏
  • 举报
回复
你到底是需要输入回车还是不输入?
也不知道是我的理解能力有问题,还是你的语言表达能力~!·#¥%……—*
hxliurui 2003-11-27
  • 打赏
  • 举报
回复
read 也要敲回车才往下走,而且没有'\0',我的目的是:

char str[90];
if 敲回车
strcpy(str, "file.dat");
else
输入的字符

怎么实现?马上给分



blh 2003-11-27
  • 打赏
  • 举报
回复
read是linux的系统调用(基本I/O)
在头文件#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
0表示stdin的file id,系统自动将进程的0、1、2三个file id留给stdin stdout stderr
read(0, &ch, 1);从stdin(标准输入)中读取一个字符,回车键字符值为10
hxliurui 2003-11-27
  • 打赏
  • 举报
回复
可恨的是scanf不输入别的字符光输回车根本就退不出来
hxliurui 2003-11-27
  • 打赏
  • 举报
回复
#include <unistd.h>

read()可以检查输入是哪个键。

但是怎样用它实现我的目的?楼上的老大,可以说的详细一点吗?
hxliurui 2003-11-27
  • 打赏
  • 举报
回复
read()在哪个头文件啊?我用的是red hat 7.3

编译说read没定义
blh 2003-11-27
  • 打赏
  • 举报
回复
#include <stdio.h>

int main()
{
char ch;
read(0, &ch, 1);

if (ch == 10)
{
printf("Press key is Enter!\n");
}
else
{
printf("Press key is %d\n", ch);
}
return 0;
}
hxliurui 2003-11-27
  • 打赏
  • 举报
回复
不是一定要用scanf,只要能实现这个功能就行了

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧