另一个数组中的安全用户输入(任何类型)

时间:2014-12-07 11:02:03

标签: c arrays pointers char

我有一些小程序的麻烦。

用户应该输入(不同类型)。但是当用户输入ZERO(" 0")时,循环应该停止,程序应该在零之前打印所有输入。

如果do-while循环结束,我想通过数组并打印所有输入 所以我试图将所有输入安全保存到另一个阵列中。不幸的是我的问题是,我无法将输入(scanf)安全地保存到另一个阵列中。我希望你能帮助我。

以下是代码:

int *iarray(unsigned int n) {
    char input[MAX];
    char key[] = "0";
    char arr[MAX]       //troublemaker
    int i = 0;
    int *iptr = malloc(n * sizeof(*iptr)); // or iptr = (int*) malloc(n * sizeof(int));
    if (iptr != NULL) {
        do {

            i++;
            printf("Geben sie Strings ein: ");
            scanf("%s", input);
            printf("%s\n", input); 

            /*
            arr[i] = *input;
            Here is the problem         
            */


            // i'd like to safe var input in another array for example arr[] and print it after the do- while loop          


        } while(strcmp(input, key) != 0); // compare if input = 0.  -> if input zero then break

    printf("Durchläufe %d\n", i);

    }
    return iptr;
}

2 个答案:

答案 0 :(得分:1)

我终于得到了我的代码的解决方案,我们走了。我非常感谢任何改进我的代码的建议。干杯;)



#define MAX 100


int *iarray(unsigned int n) {
	char input[MAX][MAX];
	char temp[MAX][MAX];
	char key[] = "0";
			
	int i = 0;
	int *iptr = malloc(n * sizeof(*iptr)); // or iptr = (int*) malloc(n * sizeof(int));
	if (iptr != NULL) {
		do {						
			i++;
			printf("Put in a strin: ");
			scanf("%s", input[i]);
			printf("%s\n", input[i]);			
			strcat(temp[i],input[i]);	// i use a temp array to safe all input stings there		
		} while(strcmp(input[i], key) != 0); 	// compare if input = 0.  -> if input zero then break

	printf("Durchläufe %d\n", i);
	int l;
	for (int k = 1; k <= i; k++) {			//first loop creates amount of input strings
		printf("\n");	
		for (l = 0; temp[l] != NULL; l++) {	// second loop prints every single letter
				if (temp[k][l] == 0) {	// if there is no if-statement i get a lot of crap from the output
					break;		
				}else{
				 	printf("%c" , temp[k][l]); // here i print my 2d arrays
				}
		}
		printf(" -> lenght %d", l);		
		
	}
	printf("\n");	
	}
	return iptr;
}
...
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以试试sprintf(arr,“%s%s”,arr,输入)。 在结束的时候,你将拥有带有所有输入的arr []

相关问题