繁体   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