2012-03-27 44 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秒。