2012-03-27 46 views
0

我正在從鍵盤讀取數字,然後我必須單獨操作每個數字(它是一個八進制到十進制轉換器)。 是否有類似於Java的charAt()方法,可以用來處理特定的數字?在字符串中定義的位置獲取字符C在C

目前,我有下面的代碼(不完全),但是在編譯的時候,它會返回「錯誤:下標值既不是數組,也不指針」

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

int main() 
{ 
    printf("Please enter an octal number ending with #"); 
    char nextNum = getchar(); 
    char number; 
    int counterUp = 0; //Records how many digits are entered 
    int counterDown = 1; //Records progress during conversion 
    int decimalNumber = 0; 

    while(nextNum != '#') //reads in the whole number, putting the characters together to form one Octal number. 
    { 
     number = (number + nextNum); 
     counterUp++; 
     nextNum = getchar(); 
    } 


    //Begin converson from Octal to Decimal 

    while(counterUp >= 0) 
    { 
     int added = (number[counterUp] * (pow(8, counterDown))); 
     decimalNumber = (decimalNumber + added); 
     counterDown++; 
    } 
} 

我不希望被告知如何從八進制去到小數點,就是如何一次處理一位數字。

+0

請發佈完整的編譯器錯誤消息,並指出代碼中編譯器標記爲不正確的行。 – 2012-03-27 01:50:29

+0

不正確的行是'int added =(number [counterUp] *(pow(8,counterDown)));' – Crashworks 2012-03-27 01:51:33

+0

由於'number'是一個單一的字符,因此它就像是一個數組類型一樣訪問沒有任何意義...使用如下建議的字符數組。 – prelic 2012-03-27 01:55:37

回答

1

使用fgets(),而不是單個字符:

char number[25]; // max of 25 characters in string 

fgets(number, 24, stdin); // read a line from 'stdin', with a max of 24 characters 
number[24] = '\0'; // append the NUL character, so that we don't run into problems if we decide to print the string 

現在你可以隨意下標number,例如number[10] = 'A'

0

我認爲你需要退一步,仔細看看你的算法。

char number是什麼存儲的?你期望這個循環做什麼:

while(nextNum != '#') //reads in the whole number, putting the characters together to form one Octal number. 
{ 
    number = (number + nextNum); 
    counterUp++; 
    nextNum = getchar(); 
} 

特別是,number = (number + nextNum);是什麼意思?

+0

nextNum從鍵盤讀入下一個數字,並且(至少我曾經認爲)至少將其附加到數字串的末尾。 – CoolerScouter 2012-03-27 02:05:01

+0

@ user1247751'char number;'不是一個字符串。這是一個單一的字符。另外,C沒有內置的字符串附加操作符。 – Crashworks 2012-03-27 02:06:04

0

您需要將數字定義爲一個字符數組。

例如

char number[16]; 

然後改變你的閱讀循環追加到數組。

while(nextNum != '#') 
{ 
    number[counterUp] = nextNum; 
    counterUp++; 
    nextNum = getchar(); 
} 
1

我想你已經習慣了Java的方式,你可以寫這樣的:

String number = ""; 
number += "3"; 
number += "4"; 

字符串用C不喜歡這個工作。此代碼不會做你認爲它的作用:

char number = 0; // 'number' is just a one-byte number 
number += '3';  // number now equals 51 (ASCII 3) 
number += '4';  // number now equals 103 (meaningless) 

也許這樣的事情會爲你工作:

char number[20]; 
int i = 0; 
number[i++] = '3'; 
number[i++] = '4'; 

或者,你可以簡單地使用scanf從鍵盤讀取數。

我建議你找一本關於C的好書,先閱讀字符串,然後再閱讀scanf秒。