[英]How can I make the next printf() to print on the same line and not below it?
我最近开始学习C,我决定制作一个使用户易于使用的计算器程序:
#include"stdio.h"
int main()
{
int a,b;
char c;
scanf("%d%c%d",&a,&c,&b);
switch(c)
{
case '+':
printf("=%d",a+b);
break;
case '-':
printf("=%d",a-b);
break;
case '*':
printf("=%d",a*b);
break;
case '/':
printf("=%d",a/b);
break;
case '%':
printf("=%d",a%b);
break;
default:
printf("\nWhat the heck is %c supposed to mean??",c);
break;
}
return 0;
}
但是,执行该问题时会遇到此问题。 即使我在printf()
命令中未使用\\n
,输出语句也会在下面一行打印,而不是在同一行继续打印。
4/2
=2
如何解决此问题,并使= 2打印在同一行上?
您在第一行中看到的是输入给用户的控制台信息,而第二行是实际的printf(实际上不打印任何换行符)。
当用户输入4/2
他按Enter键,这就是控制台中打印的内容。
如果您不希望这种情况发生,请使用getchar()
函数两次,获得三个字符,并在接收到它们后立即打印。 尽管您将不得不放置一些复杂的代码来标识第一个数字的末尾,第一个可操作字符+-*/
和第二个数字的末尾(您可以使用空格字符)。 最终这将像4/2 =2
一样打印您的输入。
或如以上评论所述,
您真正可以做的事情很简单:将输入与输出一同输出: printf("%d%c%d=%d",,a,c,b,a+b);
但是这种方法实际上会将输出以及原始输入引入控制台。
使用termios:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <termios.h>
int main()
{
int a,b, i, j;
char c, str[10];
struct termios term, term_orig;
if(tcgetattr(STDIN_FILENO, &term_orig)) {
printf("tcgetattr failed\n");
return -1;
}
term = term_orig;
term.c_lflag &= ~ICANON;
term.c_lflag &= ~ECHO;
if (tcsetattr(STDIN_FILENO, TCSANOW, &term)) {
printf("tcsetattr failed\n");
return (-1);
}
for (i =0; i < 3; i++)
{
switch (i)
{
case 0:
for(j = 0;; j++)
{
str[j] = getchar();
if (isdigit(str[j]))
putchar(str[j]);
else
break;
}
str[j] =0;
a = atoi(str);
break;
case 1:
do {
c = fgetc(stdin);
} while ( c == ' ');
putchar(c);
break;
case 2:
j = 0;
do {
str[j] = getchar();
putchar(str[j]);
} while ( str[j] == ' ');
for(j = 0;; j++)
{
str[j] = getchar();
if (isdigit(str[j]))
putchar(str[j]);
else
break;
}
str[j] =0;
b = atoi(str);
break;
}
}
switch(c)//.......
if (tcsetattr(STDIN_FILENO, TCSANOW, &term_orig)) {
printf("tcsetattr failed\n");
return -1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.