[英]Taking string as input character by charcter and giving output on pressing enter
我想用C或C ++編寫一個程序,該程序將一個字符串作為一個字符一個字符地輸入,並在按下Enter鍵時給出輸出。 我必須逐個輸入字符 。
while (1)
{
scanf("%c",&a); //cin>>a;
if(a=='\n')
break;
//do operation on the character
}
//give output
這樣的事情,但我做不到。
IIUC,您正在尋找getchar函數:
while (1)
{
char c = (char)getchar();
if(c=='\n')
break;
//do operation on the character
}
//give output
理想情況下,您的代碼應該可以正常工作。 由於scanf讀取並存儲了一個字符。 您得到的錯誤/輸出是什么?
也嘗試比較(a == 10)10是'\\ n'的ascii值
嘗試這個:
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;
}
這是一種方法:
char ch;
while(1)
{
if((ch=getchar())=='\n')
break;
}// its working fine
另一種方式:
char ch;
while(1)
{
scanf("%c",&ch);
if((ch=='\n'))
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.