如何在不分配n个空格的情况下用C输入n个字符串(n由用户输入)?



我试图解决一个输入格式如下的问题-

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

对于每个字符串输入,必须对其进行一些修改,并输出修改后的字符串。

我没有使用 malloc 为每个字符串分配单独的空间,而是尝试了这种方法:-

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()

最新更新