[英]Why are the strings being placed with a newline? I'm trying to make it take those three inputs as a string on one line
[英]How to take inputs for strings one by one in C
我必須接受如下所示的輸入,並打印相同的內容(僅包括句子):
2
I can't believe this is a sentence.
aarghhh... i don't see this getting printed.
數字2顯示了要跟隨的行數(此后為2行)。 我將所有選項scanf和fgets與各種正則表達式一起使用。
int main() {
int t;
char str[200];
scanf ("%d", &t);
while (t > 0){
/*
Tried below three, but not getting appropriate outputs
The output from the printf(), should have been:
I can't believe this is a sentence.
aarghhh... i don't see this getting printed.
*/
scanf ("%[^\n]", str);
//scanf("%200[0-9a-zA-Z ]s", str);
//fgets(str, 200, stdin);
printf ("%s\n", str);
t--;
}
}
抱歉,我已經搜索了所有相關文章,但是我找不到任何答案:所有版本的scanf()均不產生結果,而fgets()僅輸出第一句話。 提前致謝。
您應該只使用fgets()
。 請記住,它將保留換行符,因此您可能要在閱讀換行后手動將其刪除:
if(scanf("%d", &t) == 1)
{
while(t > 0)
{
if(fgets(str, sizeof str, stdin) != NULL)
{
const size_t len = strlen(str);
str[len - 1] = '\0';
printf("You said '%s'\n", str);
--t;
}
else
printf("Read failed, weird.\n");
}
}
為了簡化起見,假設輸入為“ 2 \\ none \\ ntwo \\ n”。
當您啟動程序時,在第一個scanf()
,輸入緩沖區具有所有緩沖區並指向開頭
2\none\ntwo
^
在第一個scanf()
,將消耗“ 2”,而將輸入緩沖區保留為
2\none\ntwo
^^
現在,您嘗試讀取除換行符以外的所有內容……但是緩沖區中的第一件事是換行符,因此什么也不會讀取。
建議: 始終使用fgets()
讀取整行 ,然后在您認為更好的情況下解析輸入。
要在C中使用regex,必須包含regex.h
。 在這種情況下,您不需要正則表達式。 如果您有"%[^\\n]"
,請將其替換為"%s"
。 確保包含stdio.h
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.