2011-10-18 124 views
-1

這裏,當我發現'h'我必須訪問p和h之間的值,即123,我希望它具有int並將其存儲爲123值本身我怎麼能做到這一點任何一個可以告訴我的邏輯,我寫不工作,以及如何複製的值時,指針是越來越增加將字符值轉換爲整數值

main() 
     { 
      char *ptr1 = "p123h12"; 
      int value; 
      while(*ptr1!= '\0') 
      { 
       if(*ptr1 == 'h') 
       { 
       value = (int)atoi(ptr1); 
       printf("%d\n", value); 
       } 
      ptr1++; 
      } 

     } 

回答

1

隨着sscanf代碼:

int value; 
sscanf (ptr1,"p%dh12",&value); 

更新

int i,j; 
int values[MAX_VALUES]; 
int startIdx = -1; 
char *ptr1 = "p123hxxxxp124hxxxxp123145hxxxx"; 
char buffer[16]; 
for(i=0,j=0; i<strlen(ptr1);i++) 
{ 
    if(startIdx>=0 && ptr[i] == 'h') 
    { 
     strncpy(buffer,ptr1+startIdx,i-startIdx+1); 
     buffer[i-startIdx+1]='\0'; 
     sscanf (buffer,"p%dh",&(values[j++])); 
     startIdx = -1; 
    } 
    else if(ptr[i] == 'p') 
    { 
     startIdx = i; 
    } 
}  
+0

我不能使用sscanf,我必須推廣它,因爲我可能會得到一個輸入爲p1hp123h.every每次我必須採取p和h之間的值...所以必須使用while循環和一些條件 – Manny

0

這裏有一個很好的可能出發點:

#include <stdio.h> 
#include <ctype.h> 

int main (void) { 
    char *p, *str = "p123h12p97h62p32h"; 
    int accum = 0; 

    // Process every character. 

    for (p = str; *p != '\0'; p++) { 
     // 'p' resets the accumulator. 
     // 'h' outputs the accumulator. 
     // Any digit adjusts the accumulator. 

     if (*p == 'p')  accum = 0; 
     if (*p == 'h')  printf ("Processing %d\n", accum); 
     if (isdigit (*p)) accum = accum * 10 + *p - '0'; 
    } 

    return 0; 
} 

這將正常工作,如果你輸入的字符串跟隨你指定的格式,輸出:

Processing 123 
Processing 97 
Processing 32 

如果有可能,你輸入的字符串形式不是很好,你需要添加一些防守性編碼。