【问题标题】:How to input n strings in C (n is entered by the user) without allocating n spaces?如何在C中输入n个字符串(n由用户输入)而不分配n个空格?
【发布时间】:2017-07-17 08:24:01
【问题描述】:

我试图解决一个输入格式是这样的问题-

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)多次存储用户输入字符串吗?给定的代码没有按照我想要的方式运行/接受输入。

【问题讨论】:

  • c 还是 c++?选择。在我看来像 C。
  • 问题是%[^\n] ss 不属于那里。另外,你想吃整数后面的空格:scanf("%d ", ...)
  • scanf("%[^\n]s",str); --> scanf("%[^\n]",str);。尾随 s 不是 scanset 指令的一部分。
  • @AnttiHaapala--scanf("%d ", ...)。尾随空格将导致scanf() 阻塞,等待非空格输入。 OP 也许应该这样做:scanf("%[^\n]s",str); --> scanf(" %[^\n]",str);(前导空格添加到格式字符串)。
  • 避免更改帖子性质的编辑。如果需要追加附加数据。

标签: c arrays string input scanf


【解决方案1】:

使用同一个缓冲区一次读取一行是完全可以的,只要您在继续下一行之前完全处理读入缓冲区的数据,许多程序就是这样做的。

但是请注意,您应该通过告诉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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多