2014-02-11 40 views
2

基本上,我希望我的代码的这一部分从输入的第一行读取句子的数量,然后是句子本身,并将它们存储在数组中(即使输入可以包含空格,最终阵列输入可能不是,不是首都)。 对于下面的输入如何动态创建一个字符串数组,并同时从数组条目中删除空格?

3 
one two three 
four five six (program didn't let me input another line, but just two more for the sake of the example.) 
stack over flow 

我想下面的输出

onetwothree 
fourfivesix 
stackoverflow 

的资本化还没有实现,但我想这不会很难。 我的代码:

void main(){ 
int length1, length2,i,n; 

scanf("%d", &length1); 
char *sentenceArray1[length1]; 
char tempString[100000]; 
/*The array for storing the first set of sentences, and a temporary string used 
for allocating memory in the next loop*/ 
for(i=0;i<=length1;i++){ 
     fgets(tempString, 100000, stdin); 
     sentenceArray1[i]=malloc((strlen(tempString))*sizeof(char)); 
     sentenceArray1[i]=tempString; 
     for(n=0;n<(strlen(tempString));n++){ 
       if(tempString[n]==' '){ 
         sentenceArray1[i][n]=tempString[n+1]; 
         n++; 
       } 
     printf("%s",sentenceArray1[i]); 
     } 

} 

我的实际产量如下:

one two three 
one two three 
one two three 
onettwo three 
onettwo three 
onettwo three 
onettwotthree 
onettwotthree 
onettwotthree 
onettwotthree 
onettwotthree 
onettwotthree 

我很抱歉,如果标记偏了,这是我第一次发布提问。

+1

你用malloc在一行上分配内存,然后在下一行失去对它的引用:'sentenceArray1 [i] = tempString;'。你最终得到所有指向tempString的sentenceArray [i]。你可能想要'strcpy()'或'strncpy()'tempString。 –

回答

1

考虑以下几点:

代码

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

#define MAX_STR_LEN (100000) 

int main(void) 
{ 
    int numStrings, tempIndex, modIndex, numSpaces; 
    char tempString[MAX_STR_LEN]; 

    printf("Enter number of strings: "); 
    scanf("%d", &numStrings); 

    while(getchar() != '\n') 
     continue; 

    char **modifiedStrings = malloc(numStrings * sizeof(*modifiedStrings)); 

    for(int i = 0; i < numStrings; i++) 
    { 
     printf("Enter string %d: ", i + 1); 
     fgets(tempString, MAX_STR_LEN, stdin); 

     tempIndex = numSpaces = 0; 
     while(tempString[tempIndex] != '\n') 
     { 
      if(tempString[tempIndex++] == ' ') 
       numSpaces++; 
     } 

     modifiedStrings[i] = malloc(strlen(tempString) - numSpaces + 1); 

     tempIndex = modIndex = 0; 
     while(tempString[tempIndex] != '\n') 
     { 
      if(tempString[tempIndex] != ' ') 
       modifiedStrings[i][modIndex++] = tempString[tempIndex]; 

      tempIndex++; 
     } 
     modifiedStrings[i][modIndex] = '\0'; 
    } 

    for(int i = 0; i < numStrings; i++) 
     printf("%s\n", modifiedStrings[i]); 

    return 0; 
} 

逻辑

  1. 了解多少字符串将被输入。将它们存储在一个变量中(numStrings)。
  2. 删除scanf左侧的换行符('\n')。
  3. 创建一个数组char *,每个字符串的一个元素将被输入。
  4. 获取每个字符串。将其存储到临时的char阵列(tempString)。
  5. 计算临时char字符串中的空格数(' ')。
  6. malloc只有足够的内存供您所需。
  7. 将每个字符从临时字符串复制到新字符串(modifiedStrings[i]),跳过空格。
  8. NULL'\0')附加到新的char数组的末尾,使其成为一个字符串。
  9. 高五人。

待办事项

  1. 错误检查。

示例执行

输入字符串数:3
输入串1:一二三
输入字符串2:四五六
输入串3:堆栈超过流动
onetwothree
fourfivesix
stackoverflow

相关问题