多次复制字符串

时间:2015-03-27 06:35:15

标签: c arrays string copy

我正在尝试使用c代码多次复制和用户插入字符串。我是编码新手。

 char toCopy[81];
 int numCopies;
 int i;

 printf("Enter string: ");
 scanf("%s",toCopy);

 printf("Enter number of copies: ");
 scanf("%r", numCopies);

 printf("%s * %r")

 puts("End");

3 个答案:

答案 0 :(得分:0)

您需要for(或其他循环)来执行输出的乘法运算。此外,请考虑更改printfscanf以获得正确的程序行为。

例如:

#include <stdio.h>

int main()
{
    char toCopy[81];
    int numCopies;
    int i;

    printf("Enter string: ");
    scanf("%80s",toCopy);  // 80 is a limit of string length

    printf("Enter number of copies: ");
    scanf("%d", &numCopies);  // send address of numCopies to scanf

    for(i = 0; i < numCopies; i++)   // loop for multiplication
    {
        printf("%s ", toCopy);   // correct string output
    }
    puts("\nEnd");
    return 0;
}

答案 1 :(得分:0)

问题1:

scanf("%r", numCopies);

无效。

你需要像

这样的东西
scanf("%d", &numCopies);

根据C11标准文件,第7.21.6.2章,fscanf()定义,

  

如果转换规范无效,则行为未定义。

问题2

printf("%s * %r")

也无效。您需要为printf()中提到的格式说明符提供参数。另请注意,提供给printf()的格式字符串用于打印,而不是用于评估自身。

解决方案:

您需要在代码中使用loops来实现您的目标。

答案 2 :(得分:0)

你应该使用for循环:

#include <stdio.h>
int main(void) {
int numCopy;
scanf("%d",&numCopy);
char strings[50];
scanf("%s",strings);//Or use gets(strings);
int i;// If you aren't using C99.
   for(i = 0;i<numCopy;i++) {
      printf("%s\n",strings);
   }
   return 0;
}