[英]String Only recording first word
我刚刚开始使用C语言进行编程,我正在编写一个cypher / decypher程序。 要求用户输入存储为char *的短语。 问题是程序只存储字符串的第一个单词,然后忽略它后面的所有内容。 这是获取字符串然后分析它的代码部分
int maincalc(int k) //The Calculation Function for Cyphering
{
char *s;
s=(char*) malloc(sizeof(100));
printf("Please enter the phrase that you would like to code: ");
fscanf(stdin,"%s %99[^\n]", s);
int i=0;
int n=strlen(s);
while(i<n)
{
if(s[i]>=65&&s[i]<=90) //For Uppercase letters
{
int u=s[i];
int c=uppercalc(u,k);
printf("%c",c);
}
else if(s[i]>=97&&s[i]<=122) //For Lowercase letters
{
int u=s[i];
int c=lowercalc(u,k);
printf("%c",c);
}
else
printf("%c",s[i]); //For non letters
i++;
}
free(s);
printf("\n");
return 0;
}
只需知道该怎么做才能使程序确认整个字符串的存在,而不仅仅是第一个字。 谢谢
不,没有人工作。 使用fscanf不会等待用户输入。 它只是打印“请输入短语...”然后退出fgets也做同样的事情,程序不等待输入,只打印“PLease enter ...”然后退出。
在该评论中,在编辑之前,您提到了一些先前的输入。 我的通灵调试功能告诉我,输入缓冲区中仍然存在来自先前输入的换行符。 这会
fgets(s, 100, stdin);
和
fscanf(stdin, "%99[^\n]", s);
立即返回,因为他们立即遇到表示输入结束的换行符。
在获得更多字符串输入之前,您需要从缓冲区使用换行符。 你可以用
fscanf(stdin, " %99[^\n]", s);
格式开头的空格占用输入缓冲区中的任何初始空格,或清除输入缓冲区
int ch;
while((ch = getchar()) != EOF && ch != '\n);
if (ch == EOF) {
// input stream broken?
exit(EXIT_FAILURE);
}
在使用fgets
或fscanf
获取输入之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.