簡體   English   中英

如何在c程序中而不是從文件中掃描行

[英]how to scan line in c program not from file

如何使用 C 程序掃描用戶輸入的總行?

我試過scanf("%99[^\n]",st) ,但是當我在這個掃描語句之前掃描一些東西時它不起作用。如果這是第一個掃描語句它就起作用了。

如何使用 C 程序掃描用戶輸入的總行?

讀取一行輸入的方法有很多種,您對單詞scan的使用表明您已經專注於該工作的scanf()函數。 這很不幸,因為盡管您可以(在某種程度上)使用scanf() ) 實現您想要的,但它絕對不是閱讀一行的最佳工具。

如評論中所述,您的scanf()格式字符串將在換行符處停止,因此下一個scanf()將首先找到該換行符並且它無法匹配[^\n] (這意味着換行符之外的任何內容)。 由於換行符只是另一個空白字符,在轉換前添加一個空格會悄無聲息地吃掉它;)

但現在有了更好的解決方案:假設您只想使用標准 C 函數,那么已經有一個函數可以准確地完成讀取一行的工作: fgets() 下面的代碼片段應該解釋它的用法:

char line[1024];
char *str = fgets(line, 1024, stdin); // read from the standard input

if (!str)
{
    // couldn't read input for some reason, handle error here
    exit(1); // <- for example
}

// fgets includes the newline character that ends the line, but if the line
// is longer than 1022 characters, it will stop early here (it will never 
// write more bytes than the second parameter you pass). Often you don't 
// want that newline character, and the following line overwrites it with
// 0 (which is "end of string") **only** if it was there:
line[strcspn(line, "\n")] = 0;

請注意,您可能想改為使用strchr()檢查換行符,因此您實際上知道您是否擁有整行或者您的輸入緩沖區是否很小。 在后一種情況下,您可能想再次調用fgets()

如何使用 C 程序掃描用戶輸入的總行?

scanf("%99[^\n]",st)讀取一行,差不多。

對於 C 標准庫,一行

文本流是組成的有序字符序列,每行由零個或多個字符加上一個終止換行符組成 最后一行是否需要終止換行符是實現定義的。 C11dr §7.21.2 2

scanf("%99[^\n]",st)無法讀取行尾'\n'

這就是為什么在第二次調用時, '\n'保留在stdin中以供讀取,而scanf("%99[^\n]",st)不會讀取它。

一些方法可以使用scanf("%99[^\n]",st); ,或者它的變體作為讀取用戶輸入的一個步驟,但他們遭受 1) 沒有正確處理空行"\n" 2) 遺漏罕見的輸入錯誤 3) 長行問題和其他細微差別。


首選的便攜式解決方案是使用fgets() 循環示例:

#define LINE_MAX_LENGTH 200
char buf[LINE_MAX_LENGTH + 1 + 1];  // +1 for long lines detection, +1 for \0
while (fgets(buf, sizeof buf, stdin)) {
  size_t eol = strcspn(buf, "\n");  **
  buf[eol] = '\0';  // trim potential \n
  if (eol >= LINE_MAX_LENGTH) {
    // IMO, user input exceeding a sane generous threshold is a potential hack
    fprintf(stderr, "Line too long\n");
    // TBD : Handle excessive long line
  }

  // Use `buf[[]`
}

許多平台都支持getline()讀取一行。

缺點:非 C 標准,允許黑客用長得離譜的行來淹沒系統資源。


在 C 中,沒有很好的解決方案。 什么是最好的取決於各種編碼目標。


** 我更喜歡size_t eol = strcspn(buf, "\n\r"); 在 *nix 環境中讀取可能以"\r\n"結尾的行。

scanf() 絕不能用於用戶輸入。 從用戶那里獲取輸入的最佳方式是使用 fgets()。

閱讀更多:http ://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html

char str[1024];
char *alline = fgets(str, 1024, stdin);
scanf("%[^'\n']s",alline);

我認為正確的解決方案應該是這樣的。 它對我有用。 希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM