簡體   English   中英

如何在C中輸入n個字符串(用戶輸入n)而不分配n個空格?

[英]How to input n strings in C (n is entered by the user) without allocating n spaces?

我正在嘗試解決輸入格式如下的問題-

n       // no. of strings
first string
second string
.....
nth string    // n strings to be input separated by newlines

對於每個字符串輸入,都必須對其進行一些修改,然后輸出修改后的字符串。

我沒有嘗試使用malloc為n個字符串分配單獨的空間,而是嘗試了這種方法:

char str[MAX_SIZE];
scanf("%d",&no_of_testcases);

    while(no_of_testcases -- ){

     scanf("%[^\n]s",str);

    /* some processing on the input string*/
    /* printing the modified string */

    }

每次迭代中是否不能使用相同的空間(str)多次存儲用戶輸入的字符串? 給定的代碼沒有按照我想要的方式執行/接受輸入。

只要在繼續進行下一行之前完全處理讀入緩沖區的數據,一次使用相同的緩沖區一次讀取行就可以了,很多程序都這樣做。

但是請注意,您應該通過告訴scanf()可以存儲到緩沖區中的最大字符數來防止潛在的緩沖區溢出:

char str[1024];
int no_of_testcases;

if (scanf("%d", &no_of_testcases) == 1) {
    while (no_of_testcases-- > 0) {
        if (scanf(" %1023[^\n]", str) != 1) {
            /* conversion failure, most probably premature end of file */
            break;
        }
        /* some processing on the input string */
        /* printing the modified string */
    }
}

在輸入字符串之前跳過掛起的空白是使用換行符的一種好方法,但是具有跳過輸入行上的初始空白並忽略空行的副作用,這可能有用也可能沒有用。

如果需要更精確的解析,則可以使用fgets()

暫無
暫無

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

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