我想用C或C ++编写一个程序,它按字符串输入一个字符串,按下回车键时输出。我必须逐个输入字符。
while (1)
{
scanf("%c",&a); //cin>>a;
if(a=='\n')
break;
//do operation on the character
}
//give output
类似的东西,但我无法做到。
答案 0 :(得分:1)
IIUC,您正在寻找getchar功能:
while (1)
{
char c = (char)getchar();
if(c=='\n')
break;
//do operation on the character
}
//give output
答案 1 :(得分:0)
理想情况下,您的代码应该正常运行。 由于scanf读取字符并存储它。 你得到的错误/输出是什么?
也尝试比较(a == 10) 10是'\ n'
的ascii值答案 2 :(得分:0)
试试这个:
int main()
{
char str[100],c;
int i =0;
while((c=getc(stdin)) != '\n')
{
str[i] = c;
i++;
}
str[i] = '\0';
printf("%s",str);
return 0;
}
答案 3 :(得分:-3)
这是一种方式:
char ch;
while(1)
{
if((ch=getchar())=='\n')
break;
}// its working fine
另一种方式:
char ch;
while(1)
{
scanf("%c",&ch);
if((ch=='\n'))
break;
}